HUT-XXXX 周正虎的难题 二分

这题直接二分就可以了,注意下二分的返回值,以后都最好手动模拟一下。

代码如下:

#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;

typedef long long int Int64;

Int64 N, M, seq[1000005];

Int64 sum(Int64 h)
{
    Int64 ret = 0;
    for (int i = 1; i <= N; ++i) {
        if (seq[i] > h) {
            ret += (seq[i] - h);
        }
    }
    return ret;
}

Int64 bsearch(Int64 l, Int64 r)
{
    Int64 mid, tot;
    while (l <= r) {
        mid = (l + r) >> 1;
        tot = sum(mid); 
        if (tot > M) {
            l = mid + 1;
        }
        else if (tot < M) {
            r = mid - 1;
        }
        else return mid;
    }
    return r;
}

int main()
{ 
    Int64 Max;
    while (scanf("%I64d %I64d", &N, &M) == 2) {
        Max = -1;
        for (int i = 1; i <= N; ++i) {
            scanf("%I64d", &seq[i]);
            Max = max(Max, seq[i]);
        }
        printf("%I64d\n", bsearch(0, Max));
    }
    return 0;
}
posted @ 2012-07-24 00:31  沐阳  阅读(258)  评论(0编辑  收藏  举报