B. Nick and Array
memory limit per test256 megabytes
inputstandard input
outputstandard output
He was ready to throw out the array, but his mother reassured him. She told him, that array would not be spoiled after the following operation: choose any index i (1≤i≤n) and do ai:=−ai−1.
For example, he can change array [3,−1,−4,1] to an array [−4,−1,3,1] after applying this operation to elements with indices i=1 and i=3.
Kolya had immediately understood that sometimes it’s possible to increase the product of integers of the array a lot. Now he has decided that he wants to get an array with the maximal possible product of integers using only this operation with its elements (possibly zero, one or more times, as many as he wants), it is not forbidden to do this operation several times for the same index.
Help Kolya and print the array with the maximal possible product of elements a1⋅a2⋅…an which can be received using only this operation in some order.
If there are multiple answers, print any of them.
Input
The first line contains integer n (1≤n≤105) — number of integers in the array.
The second line contains n integers a1,a2,…,an (−106≤ai≤106) — elements of the array
Output
Print n numbers — elements of the array with the maximal possible product of elements which can be received using only this operation in some order from the given array.
If there are multiple answers, print any of them.
Examples
input
4
2 2 2 2
output
-3 -3 -3 -3
input
1
0
output
0
input
3
-3 -3 2
output
-3 -3 2
思路:
由于一个数只有变成符号相反的数减一和他本身两种形态,那么我的方法是:
全部大于等于0的数变成负数,排个序(升序降序都行),
1:如果是偶数个,直接sort回原来的位置,输出就可以了。
2:如果是奇数个,将最小的数变成正数,再sort变成原来的位置,如果最小的数是-1,那么说明全部数都是-1,那么就直接,随便一个变成0,直接输出就行
代码:
#include<cstdio>
#include<cmath>
#include<cstring>
#include<ctime>
#include<iostream>
#include<cstdio>
#include<iomanip>
#include<cstring>
#include<string>
#include<cmath>
#include<stack>
#include<queue>
#include<vector>
#include<set>
#include<map>
#include<algorithm>
#define ll long long
#define dd double
#define mes(x,y) memset(x,y,sizeof(x))
using namespace std;
const int maxn=1e5+9;
const int mod=1e9+7;
ll GCD(ll a,ll b) {//最大公约数
return b == 0 ? a : GCD(b, a % b);
}
struct node{
ll number,flag;
}v[200030];
bool cmp1(node n1,node n2){
return n1.number<n2.number;
}
bool cmp2(node n3,node n4){
return n3.flag<n4.flag;
}
int main() {
std::ios::sync_with_stdio(false);
ll n, i, j, z, ero;
while (cin >> n) {
mes(v, 0);
for (i = 0; i < n; i++) {
cin >> v[i].number;
v[i].flag = i;
if (v[i].number >= 0)v[i].number = v[i].number * (-1) - 1;
}
if (n == 1) {
if (v[0].number < 0)v[0].number = v[0].number * (-1) - 1;
cout << v[0].number << endl;
continue;
}
sort(v, v + n, cmp1);
if (n % 2 != 0) {
for (i = 0; i < n; i++) {
if (v[i].number == -1)continue;
v[i].number = v[i].number * (-1) - 1;
break;
}
if (v[0].number == -1 && v[n - 1].number == -1)v[0].number = 0;
}
sort(v, v + n, cmp2);
for (i = 0; i < n; i++) {
cout << v[i].number << " ";
}
cout << endl;
}
}