二分策略对于一些找临界值的问题很有效果。许多问题从正面着手,找到最优解不好处理,但是,采用验证的思想,将解带入验证往往很容易。采用二分策略带入验证,解题往往很简单。
>、一个例子:喝水游戏
题目链接:http://hihocoder.com/problemset/problem/1095
描述
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.
输入
The first line contains N(1 <= N <= 100000, N is odd) and K(1 <= K <= 100000).
The second line contains N numbers, Little Ho's predicted number d of N rounds.
输出
Output the minimum value of T that makes Little Ho the winner.
#include<iostream>
#include<vector>
using namespace std;
int testT(vector<int>arr, int n, int t)//验证t是否符合要求
{
int i, scoreA=0, scoreB=0,temp=0;
for (int i = 1; i <= n; i++)//进行n个回合
{
temp += t;
if (temp <= arr[i])
{
scoreA++;
temp = 0;
}
else
{
scoreB++;
temp -= arr[i];
}
}
if (scoreA < scoreB)//小HO赢
return 1;
else
return 0;
}
int findMinT(vector<int>arr, int n,int maxT)//在1~maxT之间寻找临界值t 使用二分搜索策略
{
int l = 1;
int r = maxT;
int mid = (l + r) / 2;
while (l <= r)
{
if (testT(arr, n, mid))
{
r = mid - 1;
}
else
{
l = mid + 1;
}
mid = (l + r) / 2;
}
return l;
}
int main()
{
int n, k;
cin >> n >> k;
vector<int>arr(n+1);
for (int i = 1; i <= n; i++)
{
cin >> arr[i];
}
cout << findMinT(arr, n,k) << endl;//若t大于k,则一定是小HO赢,故以此为上界
system("pause");
return 0;
}