POJ 3258(二分)

来源:互联网 发布:遥感数据 分类 建模 编辑:程序博客网 时间:2024/06/06 18:46

题目链接:http://poj.org/problem?id=3258

今天做了几个二分的题,感觉代码都差不多,但是每题都会纠结一会临界值的问题。

这道题已经纠结了不知道多久。


枚举可以跳的距离mid,用cnt计数当前mid情况下所可以去掉的石头数。

如果cnt>m,说明当前mid偏大,枚举mid-1,即high=mid-1

如果cnt<m,很明显当前mid偏小,枚举mid+1,即low=mid+1

关键在于cnt=m的时候,这时候mid满足题意,但是这只是符合题意的一种情况。题目要求的是最小距离的最大值,也就说,mid应继续增大,此时low=mid+1;

#include<iostream>#include<cstdio>#include<cstring>#include<algorithm>#include<cmath>#include<queue>using namespace std;const int INF=0x3f3f3f3f;const int maxn=50010;int L,n,m;int d[maxn];int main(){#ifndef ONLINE_JUDGE    freopen("test.in","r",stdin);    freopen("test.out","w",stdout);#endifwhile(~scanf("%d%d%d",&L,&n,&m)){int low=0,high=L,mid;d[0]=0;d[n+1]=L;for(int i=1;i<=n;i++){scanf("%d",&d[i]);}sort(d,d+(n+2));int cnt,index;while(low<=high){mid=(low+high)>>1;cnt=0,index=0;for(int i=1;i<=n+1;i++){if(mid>=d[i]-d[index])cnt++;elseindex=i;}if(cnt<=m){low=mid+1;}else{high=mid-1;}}printf("%d\n",low);}return 0;}


0 0