POJ-3258-River Hopscotch

地址:http://poj.org/problem?id=3258

思路:二分答案,一开始我始终坚信可以用贪心来写,然后就思维固化了,完全没有去想二分。然后就一直wa...

对于要求的答案ans, 0<=ans<=L,因此可以二分ans来求解,想到二分后实在是一发AC

Code:

#include<iostream>
#include<algorithm>
using namespace std;

const int MAX_N=5e4+5;
int n,m,L;
int a[MAX_N];

bool judge(int h);
int main()
{
	ios::sync_with_stdio(false);
	cin>>L>>n>>m;
	for(int i=0;i<n;++i)
		cin>>a[i];
	a[n++]=L;
	sort(a,a+n);
	int l=0,r=1e9+5,h;
	while(l<=r){
		h=(l+r)/2;
		if(judge(h))	l=h+1;
		else	r=h-1;
	}
	cout<<r<<endl;
	
	return 0;
}

bool judge(int h)
{
	bool boo=true;
	int l=0,s=0;
	for(int i=0;i<n;++i)
		if(a[i]-l<h)	++s;
		else	l=a[i];
	if(s>m)	boo=false;
	
	return boo;
}

 

相关文章: