洛谷2678 跳石头

链接:https://www.luogu.org/problemnew/show/P2678#sub

经典的二分答案题

#include <cstdio>
#include <algorithm>
#include <cstring>

using namespace std;

const int maxSize=50000;
int l1,n,m;
int a[maxSize+5];

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

int main()
{
	int i,l,r,mid;
	
	freopen("a.txt","r",stdin);
	scanf("%d%d%d",&l1,&n,&m);
	for (i=1;i<=n;i++)
		scanf("%d",&a[i]);
	a[i]=l1;
	
	l=1;	r=l1;
	while (l<=r)//二分答案 
	{
		mid=(l+r)/2;
		if (ans(mid)==true)
			l=mid+1;
		else
			r=mid-1;
	}
	printf("%d\n",r);
	
	return 0;
}

猜你喜欢

转载自blog.csdn.net/scutbenson/article/details/82186726