根据n的奇偶情况进行分类讨论
如果n是偶数:
那么2个数2个数之间进行配对,就可以构造出结果。
例如:1 -3 --> -3 -1
如果n是奇数:
那么前n-3个数同偶数的操作。后n-3个根据抽屉原理,一定存在两个符号相同的数。
如 -3 -4 5, 构造方法如下:
b[i]=b[j]=5(等于除了符号相同那两个之外的一个数)
b[k]=-[-3+(-4)] = 7
得到:
-3 -4 5
5 5 7 对应位置相乘相加还是0
#include <iostream>
#include <cstring>
using namespace std;
const int N = 1e5 + 10;
int a[N];
void solve()
{
int n;
cin >> n;
for (int i = 0; i < n; i++)
cin >> a[i];
if (n % 2 == 0)
{
// 偶数 两两一对进行构造
for (int i = 0; i < n; i += 2)
{
cout << -a[i + 1] << " " << a[i] << " ";
}
}
else
{
// 先取三个,然后剩余的也正好是偶数个
int x = a[n - 3], y = a[n - 2], z = a[n - 1];
for (int i = 0; i < n - 3; i += 2)
{
cout << -a[i + 1] << " " << a[i] << " ";
}
// x y符号相同
if(x > 0 && y > 0 || x < 0 && y < 0)
{
int temp = -(x + y);
cout << z << " " << z << " " << temp;
}
else if(x > 0 && z > 0 || x < 0 && z < 0)
{
int temp = -(x + z);
cout << y << " " << temp << " " << y;
}
else if(y > 0 && z > 0 || y < 0 && z < 0)
{
int temp = -(y + z);
cout << temp << " " << x << " " << x;
}
}
puts("");
}
int main()
{
int T;
scanf("%d", &T);
while (T--)
{
solve();
}
}