Luogu题目链接:https://www.luogu.org/problem/P1588
思路:有三种走法,x+1,x-1,x*2 可以宽搜做此题
x坐标+1 x坐标-1 x坐标*2
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| #include <bits/stdc++.h> using namespace std; #define maxn 1000000 int used[maxn]; struct node{ int x,t; };
int bfs(int x,int y){ queue<node> q; q.push((node){x,0}); while(!q.empty()){ node n; n=q.front(); q.pop(); for(int i=1;i<=3;i++){ node v; v.t=n.t+1; if(i==1) v.x=n.x-1; if(i==2) v.x=n.x+1; if(i==3) v.x=n.x*2; if(v.x<1||v.x>maxn) continue; if(used[v.x]) continue; if(v.x==y) return v.t; used[v.x]=1; q.push(v); } } } int main(){ int n; int a,b; cin>>n; while(n--){ memset(used,0,sizeof(used)); cin>>a>>b; if(a==0) cout<<0; cout<<bfs(a,b)<<endl;} }
|