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

题目链接: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;
}
posted @ 2020-10-13 23:20  Kanoon  阅读(122)  评论(0编辑  收藏  举报