深度优先搜索,队列
#include <iostream> #include <cstdio> #include <cstring> #include <queue> using namespace std; const int MAXN = 100001; struct Status{ int n, t; Status(int n, int t): n(n), t(t) {} }; bool visited[MAXN]; int BFS(int n, int k){ queue<Status> myQueue; myQueue.push(Status(n, 0)); visited[n] = true; while(!myQueue.empty()){ Status now = myQueue.front(); myQueue.pop(); if(now.n == k){ return now.t; } for(int i = 0; i < 3; i++){ Status next(now.n, now.t + 1); if(i == 0){ next.n += 1; }else if(i == 1){ next.n -= 1; }else{ next.n *= 2; } if(next.n < 0 || next.n >= MAXN || visited[next.n] == true){ continue; } myQueue.push(next); visited[next.n] = true; } } } int main(){ int n, k; while(cin >> n >> k){ memset(visited, false, sizeof(visited)); //!!!!!!一定要记得初始化 printf("%d\n", BFS(n, k)); } return 0; }