二分贪心专题D

The annual Games in frogs' kingdom started again. The most famous game is the Ironfrog Triathlon. One test in the Ironfrog Triathlon is jumping. This project requires the frog athletes to jump over the river. The width of the river is L (1<= L <= 1000000000). There are n (0<= n <= 500000) stones lined up in a straight line from one side to the other side of the river. The frogs can only jump through the river, but they can land on the stones. If they fall into the river, they 
are out. The frogs was asked to jump at most m (1<= m <= n+1) times. Now the frogs want to know if they want to jump across the river, at least what ability should they have. (That is the frog's longest jump distance).
InputThe input contains several cases. The first line of each case contains three positive integer L, n, and m. 
Then n lines follow. Each stands for the distance from the starting banks to the nth stone, two stone appear in one place is impossible. OutputFor each case, output a integer standing for the frog's ability at least they should have. Sample Input
6 1 2
2
25 3 3
11 
2
18

Sample Output

4

11

青蛙跳过河,河上有若干个石头,青蛙共跳m次,问青蛙过河一次跳最远的最小值是多少。

方法是二分答案。

首先二分上界是河的宽度 下界是相邻两块石头的最大间距(二分范围尽量缩小,但注意保证正确性)

bool Check(int a[],int n,int m,int x)
{
	int i=0,step=0,j=1;
	bool flag;
	while (j<n)
	{
		flag=true; 
		while (j<n&&a[j]-a[i]<=x)
		{
			j++; 
			flag=false;
		}
		i=j-1;
		if (flag) return false;
		step++; 
		if (step>m) return false;
	}
	return true;
}

对于二分出的答案x,当两块石头的间距小于x时就不断扩大,当最小间距石块不满足时和走过的步数大于m时此方案不可行。

源代码:

#include<iostream>
#include<algorithm>
using namespace std;
int a[500002];

bool Check(int a[],int n,int m,int x)
{
	int i=0,step=0,j=1;
	bool flag;
	while (j<n)
	{
		flag=true; 
		while (j<n&&a[j]-a[i]<=x)
		{
			j++; 
			flag=false;
		}
		i=j-1;
		if (flag) return false;
		step++; 
		if (step>m) return false;
	}
	return true;
}


int main()
{
	a[0]=0; 
	int l,n,m,left,right,i,mid;
	while (cin>>l>>n>>m)
	{
		for (i=1;i<n+1;i++) scanf("%d",&a[i]);
		sort(a,a+n+1); 
		a[n+1]=l, 
		left=a[1];
		right=l;
		n=n+2; 
		while (left<right)
		{
			mid=(left+right)/2;
			if (!Check(a,n,m,mid)) left=mid+1;
			else right=mid; 
		}
		cout<<left<<endl;
	}
	return 0;
}


猜你喜欢

转载自blog.csdn.net/ruozhalqy/article/details/54780941