Description
Children in a kindergarten have received a large sack containing M candies. It has been decided that the candies are to be distributed among N children.
Each child has stated the number of candies that itwants. If a child isn’t given the amount of candy it wants, it will get angry. In fact it’ll get angrierfor each candy it is deprived of. Some speculate that it’s anger will be equal to the square of the number of candy it is deprived of. For instance, if Mirko states that he wants 32 candies but receives only 29, he would be missing 3 candies, so his anger would be
equal to 9.
Unfortunately, there is an insufficient amount of candy to satisfy all children. Therefore, the candies
should be distributed in such a way that the sum ofthe children’s anger is minimal.
Input
The following Nlines contain integers (one per line) which represent the wishes of the children. Those
numbers are all strictly less than 2·10 9, and their sum always exceeds M.
Output
Note: The test cases will ensure that the result fits in a 64-bit unsigned integer: int64in Pascal, long long
in C/C++, longin Java.
Sample Input
5 3 1 3 2 10 4 4 5 2 3
Sample Output
1 4
题意:有m个糖果,n个孩子,每个孩子都有自己所需要的糖果数,现在你去分配糖果,如果孩子要x个糖果儿你只给了y个,那么愤怒值就是(x-y)^2,现在要愤怒值最小
思路:这道题很容易想到的就是让每个孩子所差的个数都平均求得最小,但是提交却一直RE,我就郁闷了,后来才发现居然是因为long long的问题,改为unsigned型才A了
#include <stdio.h>
#include <iostream>
#include <string.h>
#include <algorithm>
using namespace std;
unsigned long long a[100005];
int main()
{
unsigned long long sum,ans,k,n,m,i,j,tem,r;
while(cin>>m>>n)
{
sum = ans = 0;
for(i = 0; i<n; i++)
{
cin>>a[i];
sum+=a[i];
}
sort(a,a+n);
k = sum-m;//还有几个未能平分
for(i = 0; i<n; i++)
{
tem = k/(n-i);//算剩下的人之中进行平分
if(tem<=a[i])
{
ans+=tem*tem;
k-=tem;
}
else//少于平均水平,全部加上
{
ans+=a[i]*a[i];
k-=a[i];
}
}
cout<<ans<<endl;
}
return 0;
}