Description
LLNNDiDiL).
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.
MN).
*before*M
Input
LNM
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.
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
M
Sample Input
25 5 2 2 14 11 21 17
Sample Output
4
解题思路:
一开始题意并不太好理解。稍微转换一下思路,给定N+2个石头,从中选出N+2-M个石头使他们之间最小的距离最大。
那么我们如何切入呢 我们利用二分查找 查找一个p是不是这个最短距离
怎么设置check函数呢? 我们这样看 如果当前p可以 那么我第一个起始点肯定要(为了最长)然后下一个点 如果大于now+p,
注意这里二分要更新left 因为它左边是满足的 右边不满足 相当于斜率为负数的斜线找零点
#include <cstdio> #include <iostream> #include <cstring> #include <cmath> #include <algorithm> #include <map> using namespace std; #define dbg(x) cout<<#x<<" = "<< (x)<< endl int l,n,m,sum; const int MAX_N = 50005; int dis[MAX_N]; int check(int p){ int now = 0; int sum_now = 1; for(int i = 1;i<=n+1;++i){ if(dis[i]>=(now+p)){ now = dis[i]; sum_now++; //dbg(sum_now); //num--; } if(sum-sum_now>(n+1-i)) { //dbg(i); //dbg(sum-sum_now); //dbg(n+1-i); break; } } //dbg(sum_now); if(sum_now>=sum) return 1; else return 0; } int main(){ scanf("%d%d%d",&l,&n,&m); dis[0] = 0; dis[n+1] = l; for(int i = 1;i<=n;++i) scanf("%d",&dis[i]); sort(dis,dis+n+2); sum = n+2-m; int left = 0,right=l*2; while(left<=right){ //dbg(left); //dbg(right); int mid =(left+right)>>1; if(check(mid)) left = mid+1; else right = mid-1; //printf("----%d\n",right); } printf("%d\n",right); return 0 ; }
文章来源: River Hopscotch 二分查找