题目是青蛙跳石头,给定距离、中间石头及步数,求每步跳的最短距离
L,n都比较大,这里用二分找距离
代码:
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
int L,n,m;
int stone[500005],dis[500009];
int Binary_search(int low,int high)
{
int count,i;
int mid;
int temp;
while(low<=high)
{
mid=(low+high)/2;
count=0;//记录步数
i=0;
while(i<=n && count<=m)
{
count++;
temp=mid;
while(temp-dis[i]>=0 && i<=n) //跳到能跳到的最远点
{
temp-=dis[i];
i++;
}
}
if(count<=m && i>n) high=mid-1; //步数还没走完就跳到终点了 说明可能还可以减小每步距离
else low=mid+1;
}
return low;
}
int main()
{
int i;
int max,ans;
while(scanf("%d%d%d",&L,&n,&m)!=EOF)
{
memset(stone,0,sizeof(stone));
memset(dis,0,sizeof(dis));
stone[0]=0;
for(i=1;i<=n;i++)
{
scanf("%d",&stone[i]);
}
stone[n+1]=L;//把原点和终点当做距离为0和L的石头 题目就变成从0石头跳到L石头上
sort(stone,stone+n+2);
max=0;
for(i=0;i<=n;i++)
{
dis[i]=stone[i+1]-stone[i];
if(max<dis[i]) max=dis[i];//答案必定大于等于相邻间距最大的 即[max,L]
}
if(m==n+1) printf("%d\n",max); //步数刚好可以跳所有石头 那就直接按间距最大的方法跳
else//步数不够情况
{
ans=Binary_search(max,L);
printf("%d\n",ans);
}
}
return 0;
}