Catch That Cow
阿新 • • 發佈:2020-07-22
Catch That Cow
BFS很簡單,有三種方向,按BFS板子走一遍就行了
//#include <bits/stdc++.h> #include <cstring> #include <iostream> #include <set> #include <queue> #include <stack> using namespace std; typedef long long ll; typedef unsigned long long ull; int mod = 9973; const int INF = 0x3f3f3f3; const int maxn = 1e5 + 10; int vis[maxn];//檢測是否來過,來過了再走一遍就沒意義了 int n, k; struct node { int step; int x; };//這道題要記錄步數,所以用結構體 int main() { cin >> n >> k; if (k <= n) { cout << n - k;//後退只有一種方法 return 0; } queue<node> q; node tem; tem.step = 0; tem.x = n; q.push(tem); vis[n] = 1; while (!q.empty()) { node t = q.front(); q.pop(); node t1, t2, t3; t1.step = t2.step = t3.step = t.step + 1; t1.x = t.x - 1, t2.x = t.x + 1, t3.x = t.x * 2; if (t1.x == k || t2.x == k || t3.x == k) { cout << t1.step; return 0; } if (t1.x >= 0 && (!vis[t1.x])) { q.push(t1); vis[t1.x] = 1; } if (!vis[t2.x]) { q.push(t2); vis[t2.x] = 1; } if (t3.x < maxn && (!vis[t3.x])) { q.push(t3); vis[t3.x] = 1; } } return 0; }