題目鏈接;點擊打開鏈接
題意:有一條小河長爲M的小河,可以看作一維軸,小河裏存在N個石頭,有一個每次能跳L米的小青蛙,隨意添加石頭保證青蛙能從頭跳到尾的,問青蛙使用最優策略跳到對岸最多需要多少次。
思路:不妨假設青蛙每個石頭都要經過一次,用step表示青蛙上一次跳的步長,每跳一次對目前點到下一點的距離和step的和與L做比較,如果小與,證明青蛙可以一次跳到這,更新step和青蛙位置,cnt保持不變,若大於,證明青蛙至少需要再跳一次,若length<=l,則直接跳,更新step=length,cnt++;若length>l,則讓青蛙以l+1-step,step,的週期跳,易證可以保證解最優,然後相當於把石頭向後平移x*(l+1)個單位。and so on。詳情請看代碼,非常明瞭~比賽的時候手殘wa到哭!!!
cpp:
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cmath>
using namespace std;
int data[200010],T,n,m,l;
void slove()
{
sort(data,data+n+1);
int step=l,now=0,cnt=0;
for(int i=0;i<=n;i++){
int length=data[i]-now;
if(length==0) continue;
if(length+step<=l){
now=data[i];
step=length+step;
}
else if(length<=l){
now=data[i];
step=length;
cnt++;
}
else if(length>l){
int tp=length%(l+1);
cnt+=(length/(l+1))*2;
if(tp+step<=l){
step=tp+step;
now=data[i];
}
else {
step=tp;
now=data[i];
cnt++;
}
}
}
printf("%d\n",cnt);
}
int main()
{
//freopen("data.in","r",stdin);
int cas=0;
scanf("%d",&T);
while (T--){
printf("Case #%d: ",++cas);
scanf("%d%d%d",&n,&m,&l);
for(int i=0;i<n;i++){
scanf("%d",data+i);
}
data[n]=m;
slove();
}
return 0;
}