题目地址:POJ 3258
水题。二分距离,判断是否可行。需要注意的是最后一个,因为最后一个是没法移除的,所以还要倒着判断一下。
代码如下:
#include <iostream>
#include <string.h>
#include <math.h>
#include <queue>
#include <algorithm>
#include <stdlib.h>
#include <map>
#include <set>
#include <stdio.h>
using namespace std;
#define LL __int64
#define pi acos(-1.0)
const int mod=9901;
const int INF=0x3f3f3f3f;
const double eqs=1e-8;
int a[51000], vis[51000];
int bin_search(int n, int m)
{
int low=0, high=1e9, mid, ans, cnt, last;
while(low<=high) {
mid=low+high>>1;
int flag=0;
cnt=0;
last=0;
memset(vis,0,sizeof(vis));
for(int i=0; i<n; i++) {
if(a[i]-last<mid) {
cnt++;
if(cnt>m)
break;
} else {
last=a[i];
vis[i]=1;
}
}
for(int i=n-1;i>=0;i--){
if(vis[i]){
if(a[n]-vis[i]<mid){
cnt++;
if(cnt>m) break;
}
else break;
}
}
if(cnt>m) high=mid-1;
else{
ans=mid;
low=mid+1;
}
}
return ans;
}
int main()
{
int lenth, i, n, m, ans;
scanf("%d%d%d",&lenth,&n,&m);
for(i=0; i<n; i++) {
scanf("%d",&a[i]);
}
if(!n) {
printf("%d\n",lenth);
return 0;
}
sort(a,a+n);
a[n]=lenth;
ans=bin_search(n,m);
printf("%d\n",ans);
return 0;
}
原文地址:http://blog.csdn.net/scf0920/article/details/43060983