星际跃迁追踪协议
#include<bits/stdc++.h>
using namespace std;
long long n,m,vis[1000005];
struct lnt{
long long x,z;};
queue<lnt> a;
int main(){
cin>>n>>m;
a.push({n,0});
while(a.size()){
lnt f=a.front();
if(f.x==m){
cout<<f.z;
return 0;
}
if(f.x<=2*m&&f.x>0){
if(vis[f.x*2]==0){//*2的路线
a.push({f.x*2,f.z+1});
vis[f.x*2]=1;
}
if(vis[f.x-1]==0){//-1的路线
a.push({f.x-1,f.z+1});
vis[f.x-1]=1;
}
if(vis[f.x+1]==0){//+1的路线
a.push({f.x+1,f.z+1});
vis[f.x+1]=1;
}
a.pop();
}else{
a.pop();//进行下一次广搜
}
}
return 0;}
跳跃机器人
#include<bits/stdc++.h>
using namespace std;
long long n,m,vis[10000005];
struct lnt{
long long x,z;};
queue<lnt> a;
int main(){
cin>>m;
n=1;//设起始点是1
a.push({n,0});
while(a.size()){
lnt f=a.front();
if(f.x==m){
cout<<f.z;
return 0;
}
if(f.x<=m&&f.x>0){//判断是否超边界
if(vis[f.x*2]==0){
a.push({f.x*2,f.z+1});
vis[f.x*2]=1;
}
if(vis[f.x-1]==0){
a.push({f.x-1,f.z+1});
vis[f.x-1]=1;
}
if(vis[f.x+1]==0){
a.push({f.x+1,f.z+1});
vis[f.x+1]=1;
}
a.pop();
}else{
a.pop();
}
}
return 0;}
影分身过河
#include<bits/stdc++.h>
using namespace std;
long long n,t[2005],vis[1000005];
struct lnt{
long long x,z;};
queue<lnt> a;
int main(){
cin>>n;
for(int i=1;i<=n;i++) cin>>t[i];
a.push({1,0});
while(a.size()){
lnt f=a.front();
if(f.x>=n){
cout<<f.z;//输出步数
return 0;
}
if(f.x<=2*n&&f.x>0){//判断边界
if(t[f.x]>0){
for(int i=1;i<=t[f.x];i++){
int j=f.x+i;
if(vis[j]==0){
vis[j]=1;
a.push({j,f.z+1});
}
}
}else{
for(int i=1;i<=f.x+t[f.x];i++){
if(vis[i]==0){
vis[i]=1;
a.push({i,f.z+1});
}
}
}
}
a.pop();
}
cout<<-1;
return 0;}
Catch That Cow S
#include<bits/stdc++.h>
using namespace std;
long long n,m,T,vis[10000005];
struct lnt{
int x,z;};
queue<lnt> a;
int main(){
cin>>T;
while(T--){
while(a.size()) a.pop();
for(int i=1;i<=5e5;i++) vis[i]=0;//清空
cin>>n>>m;
vis[n]=1;
vis[m]=0;
a.push({n,0});
while(a.size()){
lnt f=a.front();
if(f.x==m){
cout<<f.z<<"\n";
break;
}
if(f.x<=3*m&&f.x>0){//边界
if(vis[f.x*2]==0){
a.push({f.x*2,f.z+1});
vis[f.x*2]=1;
}
if(vis[f.x-1]==0){
a.push({f.x-1,f.z+1});
vis[f.x-1]=1;
}
if(vis[f.x+1]==0){
a.push({f.x+1,f.z+1});
vis[f.x+1]=1;
}
}
a.pop();
}
}
return 0;
}