SOJ3916 && ZAFU1191:LJUTNJA(贪心)

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 first line contains two integers, M(1 ≤ M≤ 2·10 9) and N(1 ≤ N≤ 100 000).  
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

The first and only line of output must contain the minimum sum of the children’s anger.  
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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值