hdu 4004 The Frog's Games (二分搜索 + 贪心)
2013-09-10 21:35
411 查看
原题友情链接~点击此处打开链接~
一道很好的二分的题目。一开始不会= =。看了下别人的博客。觉得好简单= =。
先说下题意:
三个数据l,n,m。l表示河的宽度,n,表示河水中间有n块石头,m表示小青蛙跳过河所需的最多步数。然后让你输出青蛙每步跳的最短距离。
青蛙要跳过河,要求每步的距离最短,假设青蛙在跳跃的时候一个石头一个石头的跳,则可知青蛙要跳过河,跳跃距离在范围[maxlen,l]之间,maxlen表示相邻的两石头间的最长距离。然后再这个范围内二分枚举出最佳长度。
对于每一次的跳跃,有点贪心的思想,每次跳跃到哪个石子的选择,就是选择 离当前跳跃到的位置最近的石子。
具体实现看代码
一道很好的二分的题目。一开始不会= =。看了下别人的博客。觉得好简单= =。
先说下题意:
三个数据l,n,m。l表示河的宽度,n,表示河水中间有n块石头,m表示小青蛙跳过河所需的最多步数。然后让你输出青蛙每步跳的最短距离。
青蛙要跳过河,要求每步的距离最短,假设青蛙在跳跃的时候一个石头一个石头的跳,则可知青蛙要跳过河,跳跃距离在范围[maxlen,l]之间,maxlen表示相邻的两石头间的最长距离。然后再这个范围内二分枚举出最佳长度。
对于每一次的跳跃,有点贪心的思想,每次跳跃到哪个石子的选择,就是选择 离当前跳跃到的位置最近的石子。
具体实现看代码
#include<cstdio> #include<cstring> #include<iostream> #include<algorithm> using namespace std; const int vMaxsize = 500050; int L,n,m,data[vMaxsize]; int solve(int len)/*求出当前len过河的步数*/ { int i = 1,cnt = 0,s = 0; while(s < L) { s += len; while(data[i] <= s ) { i++; } s = data[i-1]; cnt++; } return cnt; } int binary(int low,int high)/*在[maxlen,L]范围内二分最佳len*/ { int l = low,r = high,mid; while(l < r) { mid = (l + r)/2; if(solve(mid) <= m) { r = mid; } else { l = mid+1; } } return l; } int main() { while(scanf("%d %d %d",&L,&n,&m)!=EOF) { memset(data,0,sizeof(data)); for(int i = 1 ; i <= n ; i++) { scanf("%d",&data[i]); } sort(data,data+n+1); data[n+1] = L; data[n+2] = L*2; int maxlen = -1; for(int i = 1 ; i <= n+1 ; i++) { if(data[i] - data[i-1] > maxlen) { maxlen = data[i] - data[i-1]; } } int ans = binary(maxlen,L); printf("%d\n",ans); } return 0; }
相关文章推荐
- HDU 4004 The Frog's Games (二分 + 贪心 青蛙跳石头)
- HDU 4004 The Frog's Games(2011年大连网络赛 D 二分+贪心)
- [HDU 4004] The Frog's Games 二分+贪心
- HDU 4004 The Frog's Games (二分贪心)
- HDU 4004 The Frog's Games (二分 + 贪心 青蛙跳石头)
- HDU 4004 The Frog's Games (二分 + 贪心 青蛙跳石头)
- HDU 4004 The Frog's Games(基本算法-贪心,搜索-二分)
- HDU 4004 The Frog's Games (二分 + 贪心 青蛙跳石头)
- HDU 4004 The Frog's Games 二分+贪心
- HDU 4004 The Frog's Games (二分 + 贪心 青蛙跳石头)
- HDU 4004 The Frog's Games (二分 + 贪心 青蛙跳石头)
- 题解: HDU 4004 The Frog's Games (二分搜索)
- HDU 4004 The Frog's Games 二分+贪心
- HDU 4004 The Frog's Games (二分 + 贪心 青蛙跳石头)
- HDU 4004 The Frog's Games (二分 + 贪心 青蛙跳石头)
- HDU 4004 The Frog's Games(二分+贪心)
- hdu 4004 The Frog's Games(二分最小化最大值)
- HDU 4004 The Frog's Games(二分)
- HDU--杭电--4004--The Frog's Games--二分
- HDU:4004 The Frog's Games<二分>