Codeforces Round #352 (Div. 1) B. Robin Hood 二分

B. Robin Hood

题目连接:

http://www.codeforces.com/contest/671/problem/B

Description

We all know the impressive story of Robin Hood. Robin Hood uses his archery skills and his wits to steal the money from rich, and return it to the poor.

There are n citizens in Kekoland, each person has ci coins. Each day, Robin Hood will take exactly 1 coin from the richest person in the city and he will give it to the poorest person (poorest person right after taking richest's 1 coin). In case the choice is not unique, he will select one among them at random. Sadly, Robin Hood is old and want to retire in k days. He decided to spend these last days with helping poor people.

After taking his money are taken by Robin Hood richest person may become poorest person as well, and it might even happen that Robin Hood will give his money back. For example if all people have same number of coins, then next day they will have same number of coins too.

Your task is to find the difference between richest and poorest persons wealth after k days. Note that the choosing at random among richest and poorest doesn't affect the answer.

Input

The first line of the input contains two integers n and k (1 ≤ n ≤ 500 000, 0 ≤ k ≤ 109) — the number of citizens in Kekoland and the number of days left till Robin Hood's retirement.

The second line contains n integers, the i-th of them is ci (1 ≤ ci ≤ 109) — initial wealth of the i-th person.

Output

Print a single line containing the difference between richest and poorest peoples wealth.

Sample Input

4 1
1 1 4 2

Sample Output

2

题意

每次你要让最大数减一,然后让最小数加一

然后操作k次

问你最大值减去最小值是多少

题解:

首先这道题模拟是可以的,但是太麻烦了……

所以还是直接二分就好了

二分一个最小值

然后再二分一个最大值

因为你会加k,使得小于那个最小值的数都加成为大于等于他的数

你会减去k,使得大于那个数,都降为小于等于的那个数

所以直接二分就完啦

代码

#include<bits/stdc++.h>
using namespace std;
const int maxn = 5e5+7;
int n,k,a[maxn];
long long sum=0;
int main()
{
    scanf("%d%d",&n,&k);
    for(int i=1;i<=n;i++)scanf("%d",&a[i]),sum+=a[i];
    sort(a+1,a+1+n);
    int l1=sum/n,r1=(sum+n-1)/n;
    int l=0,r=l1,ansl=0;
    while(l<=r)
    {
        int mid=(l+r)/2;
        long long need=0;
        for(int i=1;i<=n;i++)if(a[i]<=mid)need+=mid-a[i];
        if(need<=k)ansl=mid,l=mid+1;
        else r=mid-1;
    }
    l=r1,r=1e9;
    int ansr=0;
    while(l<=r)
    {
        int mid=(l+r)/2;
        long long need=0;
        for(int i=1;i<=n;i++)if(a[i]>mid)need+=a[i]-mid;
        if(need<=k)ansr=mid,r=mid-1;
        else l=mid+1;
    }
    cout<<ansr-ansl<<endl;
}

你可能感兴趣的:(Codeforces Round #352 (Div. 1) B. Robin Hood 二分)