问题描述:
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);
}