In the school computer room there are n servers which are responsible for processing several computing tasks. You know the number of scheduled tasks for each server: there are mi tasks assigned to the i-th server.
In order to balance the load for each server, you want to reassign some tasks to make the difference between the most loaded server and the least loaded server as small as possible. In other words you want to minimize expression ma - mb, where a is the most loaded server and b is the least loaded one.
In one second you can reassign a single task. Thus in one second you can choose any pair of servers and move a single task from one server to another.
Write a program to find the minimum number of seconds needed to balance the load of servers.
The first line contains positive number n (1 ≤ n ≤ 105) — the number of the servers.
The second line contains the sequence of non-negative integers m1, m2, ..., mn (0 ≤ mi ≤ 2·104), where mi is the number of tasks assigned to the i-th server.
Print the minimum number of seconds required to balance the load.
2
1 6
2
7
10 11 10 11 10 11 11
0
5
1 2 3 4 5
3
In the first example two seconds are needed. In each second, a single task from server #2 should be moved to server #1. After two seconds there should be 3 tasks on server #1 and 4 tasks on server #2.
In the second example the load is already balanced.
A possible sequence of task movements for the third example is:
- move a task from server #4 to server #1 (the sequence m becomes: 2 2 3 3 5);
- then move task from server #5 to server #1 (the sequence m becomes: 3 2 3 3 4);
- then move task from server #5 to server #2 (the sequence m becomes: 3 3 3 3 3).
The above sequence is one of several possible ways to balance the load of servers in three seconds.
题目大意:给你n个数,你可以选择两个数,从一个数减一,另一个数加一。问你最少多少次这样的操作,可以让这个n个数平衡。平衡的意思是,最大的数跟最小的数的差值最小。
解题思路:最后形成的一定是“平均值”ave,和ave+1(当sum%n != 0时)。那么我们可以将n个数从小到大排序,nn = sum%n,表示最后会有nn个ave+1,和n-nn个ave。那么我们就考虑每个a[i]自身的贡献,不用考虑是减掉或者是增加,只考虑改变值。最后结果除以2,就是单方面的增或者减。
给两组样例:
5
1 1 1 5 5
5
1 1 5 5 5
前一种是期望的ave+1的个数(3个)比如果只考虑大于ave+1的数时(2个)的个数多。
后一种是期望的ave+1的个数(2个)比如果只考虑大于ave+1的数时(3个)的个数少。
#include<bits/stdc++.h>
using namespace std;
const int maxn = 1e6;
int a[maxn];
int main(){
int n;
while(scanf("%d",&n)!=EOF){
int sum = 0;
for(int i = 1; i <= n; i++){
scanf("%d",&a[i]);
sum += a[i];
}
sort(a+1,a+1+n);
int d1 = sum/n, d2 = sum/n+1;
int nn = sum%n;
int ans = 0;
for(int i = n - nn + 1; i <= n; i++){
ans += abs(a[i] - d2);
}
for(int i = 1; i <= n - nn; i++){
ans += abs(d1 - a[i]);
}
printf("%d\n",ans/2);
}
return 0;
}