二分查找

问题描述:

Little Hi and Little Ho are playing a drinking game called HIHO. The game comprises N rounds. Each round, Little Hi pours T milliliter of water into Little Ho’s cup then Little Ho rolls a K-faces dice to get a random number d among 1 to K. If the remaining water in Little Ho’s cup is less than or equal to d milliliter Little Hi gets one score and Little Ho drinks up the remaining water, otherwise Little Ho gets one score and Little Ho drinks exactly d milliliter of water from his cup. After N rounds who has the most scores wins.

Here comes the problem. If Little Ho can predict the number d of N rounds in the game what is the minimum value of T that makes Little Ho the winner? You may assume that no matter how much water is added, Little Ho’s cup would never be full.
题目链接:http://hihocoder.com/problemset/problem/1095

解决方法:
如果给定一个T值,就可以模拟出游戏进行的过程,知道比赛的结果。模拟过程复杂度为O(n)。
另外显然T值越大,小Hi赢的就越多, 就越可能符合条件,而题目要求满足条件的最小T。对于这样的求极值问题,我们可以用二分法在解空间中查找。
代码:
注意这里可能的解空间是:[1, k+1]而不是[1, k];
如果掷出的色子序列是 k, k, k, k;
给定T = k 那么结果就是小HO全胜,小Hi全败。

#include <cstdio>
#include <cstring>
#include <cmath>
enum {maxn = 100000+4};
int pre[maxn];
int n,k;
bool isOK(int T)
{
    int remain = 0;
    int lose = 0;
    for (int i=0; i< n; i++)
    {
        remain += T;
        remain -= pre[i];
        if (remain <= 0){
            remain = 0;
            lose++;
        }

    }
     if (lose >= (n+1)/2)
        return false;
    return true;

}
#define OJ
int main()
{
    #ifndef OJ
    freopen("in.txt", "r", stdin);
    #endif // OJ

    scanf("%d %d", &n, &k);
    for (int i=0; i< n; i++)
        scanf("%d", pre+i);
    int L, R;
    L = 1;
    R = k+1; //注意最大可行解为k+1,
    while(L < R){
        int M = L + (R-L)/2;
        if (isOK(M))
            R = M;
        else
            L= M+1;
    }
    printf("%d\n", R);

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值