oh yea~第一道广搜题。。好高兴~一宁哥哥给我讲的思路~
#include <iostream> #include <queue> #define SIZE 100001 using namespace std; queue<int> q; bool visited[SIZE]; int step[SIZE]; int bfs(int n, int k) { int head, next; q.push(n); visited[n] = true; step[n] = 0; while (!q.empty()) { head = q.front(); q.pop(); for (int i = 0; i < 3; i++)//对其中一种情况一搜到底。。记录所有路径 { if (i == 0) next = head - 1; else if (i == 1) next = head + 1; else next = head * 2; if (next > SIZE || next < 0 || visited[next]) continue;//如果超出界限(k的范围)或者已经访问过了 if (!visited[next]) { q.push(next); step[next] = step[head] + 1;//前一条路径数目,对应的走过的路程,即为当前的路程数 visited[next] = true; } if (next == k) return step[next];//广搜的特性,返回的第一个一定是最短的路径 } } } int main() { int n, k; cin >> n >> k; if (n >= k) cout << n - k << endl; else cout << bfs(n, k) << endl; return 0; } |