HDU 4004 The Frog's Games (二分 + 贪心 青蛙跳石头)
2017-12-24 09:43
302 查看
题意:河长L,n个石头,青蛙最多跳m次,给出n个石头在数轴上的位置,求出青蛙通过石头可以跳过河的最小跳跃能力(跳跃距离)。
思路:二分石头间的距离。
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <set>
#include <string>
#include <cstring>
#include <cmath>
using namespace std;
typedef long long ll;
int str[500005];
int len,n,m;
bool cal(int mid)
{
if(mid*m<len)
return false;
int i=0,cnt=0;
for(int j=1;j<=n+1;j++){
if(str[j]-str[i]>mid)
if(j==i+1)
return false;
else{
--j;//贪心,让每一次跳得尽可能远,
i=j;//由于为下一次循环做准备时要执行循环条件的第三部分j++,所以此处先--j。
cnt++; //例:1跳到3 再从3跳到后面,此处就是对3的处理
}
}
cnt++;
if(cnt>m)
return false;
return true;
}
int main()
{
while(scanf("%d%d%d",&len,&n,&m)==3)
{
for(int i = 1; i <= n; i++)
scanf("%d", &str[i]);
str[n+1] = len;
sort(str+1,str+n+1);
int l = 0,r = len,mid;
while(l<=r)
{
mid=(l+r)/2;
if(cal(mid))
r=mid-1;
else
l=mid+1;
}
printf("%d\n",l);
}
return 0;
}
思路:二分石头间的距离。
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <set>
#include <string>
#include <cstring>
#include <cmath>
using namespace std;
typedef long long ll;
int str[500005];
int len,n,m;
bool cal(int mid)
{
if(mid*m<len)
return false;
int i=0,cnt=0;
for(int j=1;j<=n+1;j++){
if(str[j]-str[i]>mid)
if(j==i+1)
return false;
else{
--j;//贪心,让每一次跳得尽可能远,
i=j;//由于为下一次循环做准备时要执行循环条件的第三部分j++,所以此处先--j。
cnt++; //例:1跳到3 再从3跳到后面,此处就是对3的处理
}
}
cnt++;
if(cnt>m)
return false;
return true;
}
int main()
{
while(scanf("%d%d%d",&len,&n,&m)==3)
{
for(int i = 1; i <= n; i++)
scanf("%d", &str[i]);
str[n+1] = len;
sort(str+1,str+n+1);
int l = 0,r = len,mid;
while(l<=r)
{
mid=(l+r)/2;
if(cal(mid))
r=mid-1;
else
l=mid+1;
}
printf("%d\n",l);
}
return 0;
}
相关文章推荐
- 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(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 (二分)去掉m个石头求最小间距
- 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(二分,难)