二分搜索策略_1

    二分策略对于一些找临界值的问题很有效果。许多问题从正面着手,找到最优解不好处理,但是,采用验证的思想,将解带入验证往往很容易。采用二分策略带入验证,解题往往很简单。

>、一个例子:喝水游戏

题目链接:http://hihocoder.com/problemset/problem/1095

时间限制: 10000ms
单点时限: 1000ms
内存限制: 256MB

描述

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;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值