POJ 3258 River Hopscotch(二分答案)
Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 21939 | Accepted: 9081 |
Description
Every year the cows hold an event featuring a peculiar version of hopscotch that involves carefully jumping from rock to rock in a river. The excitement takes place on a long, straight river with a rock at the start and another rock at the end, LTo play the game, each cow in turn starts at the starting rock and tries to reach the finish at the ending rock, jumping only from rock to rock. Of course, less agile cows never make it to the final rock, ending up instead in the river.
Farmer John is proud of his cows and watches this event each year. But as time goes by, he tires of watching the timid cows of the other farmers limp across the short distances between rocks placed too closely together. He plans to remove several rocks in order to increase the shortest distance a cow will have to jump to reach the end. He knows he cannot remove the starting and ending rocks, but he calculates that he has enough resources to remove up to M
FJ wants to know exactly how much he can increase the shortest distance *before* he starts removing the rocks. Help Farmer John determine the greatest possible shortest distance a cow has to jump after removing the optimal set of M rocks.
Input
Line 1: Three space-separated integers: L, N, and MLines 2..N+1: Each line contains a single integer indicating how far some rock is away from the starting rock. No two rocks share the same position.
Output
Line 1: A single integer that is the maximum of the shortest distance a cow has to jump after removing M rocksSample Input
25 5 2 2 14 11 21 17
Sample Output
4
Hint
Before removing any rocks, the shortest jump was a jump of 2 from 0 (the start) to 2. After removing the rocks at 2 and 14, the shortest required jump is a jump of 4 (from 17 to 21 or from 21 to 25).【題意】
在起點和終點之間,有 N 塊巖石(不含起點和終點的巖石),至多可以從起點和終點之間移走 M 塊巖石(不能移走起點和終點的巖石),求移走巖石後最短跳躍距離的最大值
【分析】
[NOIP2015跳石頭(原題)]
直接二分,具體詳見代碼
【代碼】
#include<cstdio> #include<algorithm> #include<iostream> #define debug(x) cerr<<#x<<" "<<x<<‘\n‘; using namespace std; inline int read(){ int x=0,f=1;char ch=getchar(); while(ch<‘0‘||ch>‘9‘){if(ch==‘-‘)f=-1;ch=getchar();} while(ch>=‘0‘&&ch<=‘9‘){x=x*10+ch-‘0‘;ch=getchar();} return x*f; } const int N=1e5+5; int ans,n,m,L,d[N]; inline bool check(int now){ int res=0,p=0;//p為前一個石頭到指向石頭的距離 for(int i=1;i<=n;i++){ if(d[i]-p<now){//如果第i個石頭到前一個石頭的距離小於假設的答案 res++;//該石頭可以搬走 } else{//如果大於(即滿足條件) p=d[i];//則保留該石頭,並將p記錄 下一個石頭到該石頭的距離 } } return res<=m; } int main(){ L=read(),n=read(),m=read(); for(int i=1;i<=n;i++) d[i]=read();d[++n]=L;//我們假設在終點處有第n+1個石頭,則他到起點的距離為L sort(d+1,d+n+1);//保證石頭有序 int l=0,r=L,mid; while(l<=r){ mid=l+r>>1; if(check(mid)){//說明二分結果小了,要向右二分 ans=mid;//記錄答案 l=mid+1; } else{ r=mid-1;//說明結果大了,要向左二分 } } printf("%d\n",ans); return 0; }
POJ 3258 River Hopscotch(二分答案)