题目链接:http://codeforces.com/problemset/problem/1180/B
B. Nick and Array
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output
Nick had received an awesome array of integers a=[a1,a2,…,an]a=[a1,a2,…,an] as a gift for his 55 birthday from his mother. He was already going to explore its various properties but after unpacking he was disappointed a lot because the product a1⋅a2⋅…ana1⋅a2⋅…an of its elements seemed to him not large enough.
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 ii (1≤i≤n1≤i≤n) and do ai:=−ai−1ai:=−ai−1.
For example, he can change array [3,−1,−4,1][3,−1,−4,1] to an array [−4,−1,3,1][−4,−1,3,1] after applying this operation to elements with indices i=1i=1and i=3i=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⋅…ana1⋅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 nn (1≤n≤1051≤n≤105) — number of integers in the array.
The second line contains nn integers a1,a2,…,ana1,a2,…,an (−106≤ai≤106−106≤ai≤106) — elements of the array
Output
Print nn 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
题目概述:给一个长度为n的数列,对于数列中的每一个数ai都可以选择把它变为-ai-1,求所构成的最大乘积,
解题思路:把一个负数变为正数对于乘积的改变是-ai-1/a=-a+1/a,是缩小的,负数相反,所以最大的乘积是把所有的正数变为负数,需要注意的是如果有奇数个数,需要保留一个正数,如果原数列有正数保留最大的正数,如果没有正数,把最大的负数变为正数
#include<iostream>
#include<algorithm>
#include<cmath>
using namespace std;
struct aa{
int i;
int abs;
}a[100005];
bool cmp1(aa x,aa y){
if(abs(x.abs)!=abs(y.abs))
return abs(x.abs)<abs(y.abs);
else{
return x.abs<y.abs;
}
}
bool cmp2(aa x,aa y){
return x.i<y.i;
}
int main(){
int n;
cin>>n;
int sum=1;
int sumo=n-(n%2);
for(int i=0;i<n;i++){
cin>>a[i].abs;
a[i].i=i;
}
int k=a[0].abs;
sort(a,a+n,cmp1);
int i;
for(i=0;i<n;i++){
// cout<<a[i].abs<<" ";
if(sumo>0){
if(a[i].abs>=0){
a[i].abs=a[i].abs+1;
a[i].abs=-a[i].abs;
sumo--;
}
else{
sumo--;
}
}
else{
break;
}
}
if(i==(n-1)){
if(a[i].abs<0){
a[i].abs=-a[i].abs-1;
}
}
sort(a,a+n,cmp2);
for(int i=0;i<n;i++){
cout<<a[i].abs<<" ";
}
// cout<<sum<<endl;
}