hdu 4004 (二分+贪心)

来源:互联网 发布:java中什么叫序列化 编辑:程序博客网 时间:2024/06/05 20:03

题意:青蛙通过河中央的n块石头过河, 所有石头均在与河岸垂直的一条线上,给定每块石头到河岸的距离,给出河的宽L,给定青蛙跳的次数上限m(即青蛙必须经过m或小于m次跳动,过到河对岸),求出青蛙能够过河的最小步长。

当步长为河宽时,青蛙必能跳过,二分步长,求最小步长。

#include <iostream>#include <algorithm>using namespace std;int const nMax = 500005;int stone[nMax];int L, n, m;bool success(int jump){if(jump * m < L) return false; int i, j, cnt;i = cnt = 0;     for(j = 1; j <= n+1; j++)        if(stone[j] - stone[i] > jump)if(j == i + 1) return false;else { i = --j; //贪心,让每一次跳得尽可能远,由于为下一次循环做准备时要执行循环条件的第三部分j++,所以此处先--j。  cnt++; }if((++cnt) > m)  //跳过河的最后一步没有记录,所以cnt要自增1。return false;return true;}bool cmp(int a, int b){return a < b;}int main(){    int l, r, mid;while(scanf("%d%d%d", &L, &n, &m) != EOF){stone[0] = 0;    for(int i = 1; i <= n; i++)            scanf("%d", &stone[i]);stone[n+1] = L;          sort(stone+1, stone+n+1, cmp);                l = 0; r = L;while(l <= r){mid = (l + r) / 2;if(success(mid))r = mid - 1;else l = mid + 1;}printf("%d\n", l); }return 0;}


 

原创粉丝点击