跳到正文

题解

题解:P14047 [SDCPC 2019] Stones in the Bucket

WhiteHoles约 1 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 1 分钟
题目
P14047

版本

  1. v1当前

题意简述

nn 个桶中有水,能抛弃或转移,求最小操作次数。

前置知识

贪心。

正解

设水量和为 sumsum。

sum=∑i=1naisum = \sum_{i = 1}^n a_i

则可以计算出最后每桶中水的数量 per=⌊(sumn)⌋per = \lfloor(\frac{sum}{n})\rfloor,采取贪心思路,对于任意 ai>pera_i > per,我们都需要加上 ai−pera_i - per,因为多余的要么转移要么抛弃。

代码

C++
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
constexpr int N = 2e5;
int T, n, a[N];
int main(void) {
	cin.tie(0) -> ios::sync_with_stdio(false);
	cin >> T;
	while (T--) {
		ll sum = 0, ans = 0;
		cin >> n;
		for (int i = 1; i <= n; ++i)
			cin >> a[i], sum += a[i];
		int per = sum / n;
		for (int i = 1; i <= n; ++i)
			if (a[i] > per)
				ans += (a[i] - per);
		cout << ans << '\n';
	}
	return 0;
}
原文