一条线上bfs搜就行
#include <iostream> #include <cstring> #include <cstdio> #include <algorithm> #include <queue> using namespace std; const int maxn=100000+100; int n,k; bool vis[maxn*2+100]; struct note { int x; int cnt; }; int bfs(int x,int y) { queue<note> q; q.push(note{x,0}); while(q.size()) { note hh=q.front(); q.pop(); int mm=hh.cnt; int xx=hh.x; int aa; aa=xx+1; if(aa>=0&&aa<=2*maxn&&!vis[aa]) { if(aa==y) return mm+1; vis[aa]=1; q.push(note{aa,mm+1}); } aa=xx-1; if(aa>=0&&aa<=2*maxn&&!vis[aa]) { if(aa==y) return mm+1; vis[aa]=1; q.push(note{aa,mm+1}); } aa=xx*2; if(aa>=0&&aa<=2*maxn&&!vis[aa]) { if(aa==y) return mm+1; vis[aa]=1; q.push(note{aa,mm+1}); } } return -1; } int main() { while(~scanf("%d%d",&n,&k)) { memset(vis,0,sizeof(vis)); if(n==k) printf("0\n"); else { int mm=bfs(n,k); printf("%d\n",mm); } } return 0; }
时间: 2024-10-12 16:44:11