本文主要是介绍【二分法】POJ3258-River Hopscotch,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
【抱大腿】啊啊啊又是一道恶心的题目!!!这道题是出在二分法里面的,因为这跟前面的一道青蛙过河的题特别像但是不一样,按照青蛙过河那个思路来走根本行不通,正好要按照跟那个思路相反的想法来想才行~
【题目】
Time Limit: 2000MS | Memory Limit: 65536K | |
xxxxxxxxx马赛克xxxxxxxxx | xxxxxxxxx马赛克xxxxxxxxx |
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, L units away from the start (1 ≤ L ≤ 1,000,000,000). Along the river between the starting and ending rocks, N (0 ≤ N ≤ 50,000) more rocks appear, each at an integral distance Di from the start (0 < Di < L).
To 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 Mrocks (0 ≤ M ≤ N).
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 ofM rocks.
Input
Lines 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
Sample Input
25 5 2 2 14 11 21 17
Sample Output
4
Hint
【代码】
#include<cstdio>
#include<algorithm>
using namespace std;int a[50001]={0},l,n,m,i;
bool fun(int m);int main()
{while(~scanf("%d%d%d",&l,&n,&m)){ int left=0,right=l,mid,ans;for(i=1;i<=n;i++)scanf("%d",&a[i]);sort(a,a+(n+1));while(right>=left){mid=(left+right)/2;//mid表示最小的距离! if(fun(mid)){left=mid+1;ans=mid;}elseright=mid-1;}printf("%d\n",ans);}
}bool fun(int mid)
{int start=0,x=0;//用start表示每次落脚点的坐标,每落一次地更新一次start for(i=1;i<=n;i++){if(a[i]-start<mid)x++;//x表示去掉的石头数,如果mid大于要跳的距离,就跳过当前这个石头,此时x++ ,并且不落地 elsestart=a[i];//此时落地! }if(l-start<mid)//判断最后一跳跳的距离要是小于mid的话那是不可以的 return false;if(x>m)//要是x>m就说明最小距离mid太大啦 return false;return true;
}
(参考了大神Rachel Zhang的代码)
这篇关于【二分法】POJ3258-River Hopscotch的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!