题意:
给定N≤105,每次操作可以使得一个数+1另一个数−1
问最少多少次操作使得amax−amin最小
分析:
显然应该让数尽可能平均,avg最好了,多的那些数则是avg+1
从最简单的思路来想,不要考虑怎么变,我们要考虑谁必须变,这里我们只考虑>的就好了
对于那些>avg的数,有sum%n个数最终结果应该avg+1,变的部分就是∑(ai−(avg−1))
如果还有>avg的数,那么应该变成avg,变的部分就是∑(ai−avg)
两部分加起来就是答案,使得问题极其简单化
代码:
//
// Created by TaoSama on 2015-12-19
// Copyright (c) 2015 TaoSama. All rights reserved.
//
//#pragma comment(linker, "/STACK:1024000000,1024000000")
#include <algorithm>
#include <cctype>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iomanip>
#include <iostream>
#include <map>
#include <queue>
#include <string>
#include <set>
#include <vector>
using namespace std;
#define pr(x) cout << #x << " = " << x << " "
#define prln(x) cout << #x << " = " << x << endl
const int N = 1e5 + 10, INF = 0x3f3f3f3f, MOD = 1e9 + 7;
int n, a[N];
int main() {
#ifdef LOCAL
freopen("C:\\Users\\TaoSama\\Desktop\\in.txt", "r", stdin);
// freopen("C:\\Users\\TaoSama\\Desktop\\out.txt","w",stdout);
#endif
ios_base::sync_with_stdio(0);
while(scanf("%d", &n) == 1) {
int sum = 0;
for(int i = 1; i <= n; ++i) {
scanf("%d", a + i);
sum += a[i];
}
sort(a + 1, a + 1 + n);
int ans = 0, avg = sum / n, delta = sum % n;
for(int i = n; i; --i) {
if(a[i] <= avg) break;
ans += a[i] - avg - (delta ? 1 : 0);
if(delta) --delta;
}
printf("%d\n", ans);
}
return 0;
}