Codeforces 672D Robin Hood

题目链接:http://codeforces.com/problemset/problem/672/D


题意:对一个序列操作k次,每次将当前最大的数中分出去1给最小的数(如果有多个最大或最小随机选择,不过不影响答案)。求最后最大的数和最小的数的差值。


思路:k<=1e9 所以我们可以用二分法来做。现在我们假设操作k次后,最小的数为x。那么所有小于x的数都要加到x,t1 = ∑(x-a[i]) ( a[i] < x ),k至少要是这么多才可以;再考虑上界,如果操作很多,会把所有的x变成x+1或者更大,这样最小值就不是x了。所以我们记录所有小于等于x的数量t2,也就是说,当前最少操作t1次,这样所有小于x的数都会变成x,然后我们还可以最多再操作t2-1次,使得当前最小数还是x(再操作t2次,最小的数就会变成x+1)。二分求解最大的数同理。


#include <cstdio>
#include <cmath>
#include <cstring>
#include <string>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#include <stack>
#include <map>
#include <set>
#include <vector>
#include <sstream>
#include <queue>
#include <utility>
using namespace std;

#define rep(i,j,k) for (int i=j;i<=k;i++)
#define Rrep(i,j,k) for (int i=j;i>=k;i--)

#define Clean(x,y) memset(x,y,sizeof(x))
#define LL long long
#define ULL unsigned long long
#define inf 0x7fffffff
#define mod %100000007
const int maxn = 500009;
LL n,k;
LL a[maxn];

void init()
{
    cin>>n>>k;
    rep(i,1,n) scanf("%I64d",&a[i]);
}

int check( LL x , int type )
{
    LL t1 = 0;
	LL t2 = 0;
	rep(i,1,n)
	if ( type == 0 )
    {
        if ( a[i] <= x )
        {
            t1 += x - a[i];
            t2++;
        }
    }
    else
    {
        if ( a[i] >= x )
        {
            t1 += a[i] - x;
            t2++;
        }
    }
	t2+=t1;
	if ( t1 > k ) return -1;
	if ( k >= t2 ) return 1;
	return 0;
}

void solve()
{
    LL S = 0;
    LL m1,m2;
    LL m,l,r;
    LL ml,mr;
    LL temp;
	ml = mr = a[1];

    rep(i,1,n)
    {
        S += a[i];
        if ( a[i] < ml ) ml = a[i];
        if ( a[i] > mr ) mr = a[i];
    }
    m1 = m2 = -1;
    l = ml;
    r = S/n;

    while( l < r )
    {
        m = ( l + r )>>1;
        temp = check(m , 0);
		if (temp == -1) r = m - 1;
		else if ( temp == 1 ) l = m + 1;
		else
		{
			m1 = m;
			break;
		}
    }
    if (m1==-1) m1 = l;

    l = (S+n-1)/n;
    r = mr;
    while( l < r )
    {
        m = ( l + r ) >> 1;
        temp = check(m , 1);
		if (temp == -1) l = m + 1;
		else if ( temp == 1 ) r = m - 1;
		else
		{
			m2 = m;
			break;
		}
    }
    if (m2==-1) m2 = l;
    printf("%I64d\n",m2-m1);
}
int main()
{
    init();
    solve();
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值