POJ-3258 River Hopscotch 二分枚举求上限

题目链接

题意:有一条河,河的长度已知,河中间有一些石头,石头的数量知道,相邻两块石头之间的距离已知。现在可以移除一些石头,问移除m块石头后,相邻两块石头之间的距离的最小值最大是多少。

思路:二分枚举答案。每 次二分枚举一个值,判断该值能够去掉多少块石头。二分枚举求上限。



#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
const int maxn = 50005;
const int inf = 1<<30;
typedef __int64 LL;
LL l;
int n,m;
LL rock[maxn];
void fun()
{
	LL ld = 0,rd = l,mid;
	int counts;
	while( ld < rd )
	{
		mid = (ld+rd)>>1;
		counts = 0;
		for( int i = 0,j = 1; j <= n+1;  )//找相邻点间最小距离
		{
			if( rock[j] - rock[i] <= mid )
			{
				j ++; counts ++;   //删除rock[j]
			}
			else{
				i = j;
				j ++;
			}
			
		}
		if( counts > m )
			rd = mid;
		else
			ld = mid+1;
	}
	printf("%d\n",rd);
}
int main()
{
	//freopen("data.txt","r",stdin);
	while( scanf("%I64d%d%d",&l,&n,&m) != EOF )
	{
		for( int i = 1; i <= n; i ++ )
			scanf("%I64d",&rock[i]);
		rock[0] = 0;rock[n+1] = l;
		sort( rock,rock+n+1 );
		fun();
	}
	return 0;
}


你可能感兴趣的:(二分查找)