Codeforces Global Round 11 A. Avoiding Zero(前缀和)

时间:2024-08-10 12:05:50

题目链接:https://codeforces.com/contest/1427/problem/A

题意

将 \(n\) 个数重新排列使得不存在为 \(0\) 的前缀和。

题解

计算正、负前缀和,如果二者和为 \(0\),则不存在满足题意的排列,否则将绝对值较大的一方排在前面即可。

代码

#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
vector<int> a(n);
int pos = 0, neg = 0;
for (auto &x : a) {
cin >> x;
(x < 0 ? neg : pos) += x;
}
if (pos + neg == 0) {
cout << "NO" << "\n";
continue;
}
if (pos + neg > 0) {
sort(a.begin(), a.end(), greater<>());
} else {
sort(a.begin(), a.end(), less<>());
}
cout << "YES" << "\n";
for (int i = 0; i < n; i++) {
cout << a[i] << " \n"[i == n - 1];
}
}
return 0;
}