第五题:E-反复横跳
分析:
- 位置从 s 到 t ,根据距离来进行确定最优跳跃,且s和t的大小关系不定,要考虑跳跃距离为 [- 20000, 20000],距离为0时不需要跳跃。
- 根据题意,如果不重置,那么每步跳跃的步长是固定的。如1,-2,4
#include<bits/stdc++.h>
using namespace std;
const int N=20005;
int dp[N*2];
int op,step,a[N],na; //na未赋值,但是是全局变量,默认为0
int main(){
op=1,step=1;
while(1){
++na;
a[na]=a[na-1]+op*step; // 下一步 长度,那么a[na]就是跳跃步长表
op=-op;step*=2; //
if(a[na]>N*10)break; // 计算达到一步长度达到10N的 步数
}
memset(dp,0x3f,sizeof(dp)); //初始化,全部赋值为0011 1111(伪无穷大)
dp[N]=0; // dp数组有2N,取中间位置为0,起点
for(int i=1;i<N;i++){ //
int x=i;
for(int j=1;j<=na;j++) // 小于跳跃步长表长度
if(a[j]<0&&x+a[j]>-x){
dp[x+N]=min(dp[x+N],dp[N+x+a[j]]+1+j); // 应该就是选择
}
x=-i;
for(int j=1;j<=na;j++)
if(a[j]>0&&x+a[j]<-x){
dp[x+N]=min(dp[x+N],dp[x+N+a[j]]+1+j);
}
} // 上面方法是把所有的距离都算出一个最优步数,然后利用数组保存
int s,t;
cin>>s>>t;
if(s==t)cout<<0<<endl;
else cout<<dp[s-t+N]-1<<endl;
return 0;
}
#include<iostream>
using namespace std;
int getStep(int a[],int distance){ // distance 为两人距离
if(distance==1){
return 1;
}else if(distance==-1){
return 2;
}
int ans=INT32_MAX; // #define INT_MAX 0x7fffffff
int to_where=0;
int step=0;
if(distance<0)
{ //如果小于0,那么要往回跳
while(to_where>distance)
{ // 找到最小的大于distance的连续步长累计和
to_where+=a[step++];
}
}
else //否则,distance大于等于0
{ while(to_where<distance) // 找到最大的小于distance的连续步长累计和
{ to_where+=a[step++]; // 找的都是不超过 t-s 的
}
}
if(to_where==distance)
{
return step; // 如果相等,意味着到达,返回步数
}
else
{ int new_distance;
new_distance=distance-to_where; // 减去一次连续跳,还差多少距离
if(abs(new_distance)<abs(distance)) //如果新的距离比原来小,可行
{ // 进行下一次连续跳跃,ans返回最小次数,最开始ans=Int_max
// step 是目前步数,局部变量,1是重置的那一次,
ans=min(ans,step+1+getStep(a,new_distance));
}
new_distance=distance-(to_where-a[step-1]-a[step-2]);//返回前2步
if(abs(new_distance)<abs(distance))
{
ans=min(ans,step-1+getStep(a,new_distance));
}
}
return ans;
}
int main(){
int s,t;
cin>>s>>t;
int distance=t-s; //两人距离t-s
int a[17];
int op=1;
int step=1;
for(int i=0;i<17;i++){ //跳跃步长表
a[i]=op*step;
op=-op;
step*=2;
}
if(distance==0){
cout<<0;
}else{
cout<<getStep(a,distance);
}
return 0;
}
https://ac.nowcoder.com/acm/contest/view-submission?submissionId=47676814