Codeforces #352 Div2 D Robin Hood(二分查找)

题目链接:
Codeforces #352 Div2 D Robin Hood
题意:
给出n个数,每次可以将最大数-1,最小数+1,问K次后最大数和最小数之差?
分析:
二分查找k次最大数的最小值y和最小数的最大值x.
如果x>=y并且这些数的和sum能被n整除则ans为0;
如果x>=y并且这些数的和sum不能被n整除则ans为1.
否则(x < y),ans为y-x.

#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
#include <climits>
#include <cmath>
#include <ctime>
#include <cassert>
#define IOS ios_base::sync_with_stdio(0); cin.tie(0);
using namespace std;
typedef long long ll;
const int MAX_N = 500010;

int n, k;
ll data[MAX_N];


bool check1(ll y)
{
    ll kk = k;
    for(int i = n - 1; i >= 0; i--){
        if(data[i] <= y ) return true;
        kk -= (data[i] - y);
        if(kk < 0) return false;
    }
    return true;
}

ll binsearch1() //最大值的最小值
{
    ll high = data[n - 1], low = data[0];
    while(high > low){
        ll mid = (high + low) >> 1;
        if(check1(mid)) high = mid;
        else low = mid + 1;
        //cout << "high = " << high << " low = " << low << endl;
    }
    return high;
}

bool check2(ll x)
{
    ll kk = k;
    for(int i = 0; i < n; i++){
        if(data[i] >= x) return true;
        kk -= (x - data[i]);
        if(kk < 0) return false;
    }
    return true;
}

ll binsearch2() //最小值的最大值
{
    ll high = data[n - 1], low = data[0];
    while(high > low + 1){ 
        ll mid = (high + low) >> 1;
        if(check2(mid)) low = mid;
        else high = mid - 1;
        //cout << "high = " << high << " low = " << low << endl;
    }
    if(check2(high)) return high;
    return low;
}

int main()
{
    IOS;
    while(cin >> n >> k){
        ll sum = 0;
        for(int i = 0; i < n; i++){
            cin >> data[i];
            sum += data[i];
        }
        sort(data, data + n);
        ll y = binsearch1();
        ll x = binsearch2();
        //cout << "y = " << y << " x = " << x << endl;
        if(x >= y) {
            if(sum % n == 0) cout << 0 << endl;
            else cout << 1 << endl;
        } else cout << y - x << endl; 
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值