https://codeforces.com/contest/1931/problem/C
要使数组中的所有元素相等,可以考虑将所有元素的平均值作为目标值。遍历整个数组,统计每个元素与目标值之间的差值的绝对值之和,即为所需的最小花费。
具体步骤如下:
- 输入t,表示测试用例的数量。
- 循环t次,对于每个测试用例,进行以下步骤:
- 输入n,表示数组的大小。
- 输入n个整数,表示数组的元素。
- 计算数组元素的平均值sum,并将其四舍五入为整数avg。
- 初始化总花费cost为0。
- 遍历整个数组,累加每个元素与avg的差值的绝对值,将结果累加到cost中。
- 输出cost。
#include <iostream> #include <vector> #include <cmath> using namespace std; int main() { int t; cin >> t; while (t--) { int n; cin >> n; vector<int> a(n); int sum = 0; for (int i = 0; i < n; i++) { cin >> a[i]; sum += a[i]; } int avg = round((double)sum / n); int cost = 0; for (int i = 0; i < n; i++) { cost += abs(a[i] - avg); } cout << cost << endl; } return 0; }