题目传送:Catch That Cow
思路:BFS找最小步数,用一个结构体存下当前结点的数值以及当前步数
AC代码:
#include <cstdio> #include <cstring> #include <string> #include <cstdlib> #include <iostream> #include <algorithm> #include <cmath> #include <queue> #include <stack> #include <vector> #include <map> #include <set> #include <deque> #include <cctype> #define LL long long #define INF 0x7fffffff using namespace std; int n, k; bool vis[200005]; struct node { int num; int cnt; node(int n, int c) : num(n), cnt(c) {}; }; int bfs(int n, int k) { if(n == k) return 0; memset(vis, false, sizeof(vis)); queue<node> que; que.push(node(n, 0)); vis[n] = true; while(!que.empty()) { node t = que.front(); que.pop(); node n1 = node(t.num - 1, t.cnt + 1); node n2 = node(t.num + 1, t.cnt + 1); node n3 = node(t.num * 2, t.cnt + 1); if(n1.num == k) return n1.cnt; if(n2.num == k) return n2.cnt; if(n3.num == k) return n3.cnt; if(n1.num >= 0 && n1.num <= 150005 && !vis[n1.num]) { //重要剪枝,num小于0的时候肯定不是正解,还有num大于150000时肯定也不是正解 que.push(n1); vis[n1.num] = true;//入队列的时候就要赋值为已经访问过,不然会超时! } if(n2.num >= 0 && n2.num <= 150005 && !vis[n2.num]) { que.push(n2); vis[n2.num] = true; } if(n3.num >= 0 && n3.num <= 150005 && !vis[n3.num]) { que.push(n3); vis[n3.num] = true; } } } int main() { while(scanf("%d %d", &n, &k) != EOF) { printf("%d\n", bfs(n, k)); } return 0; }
时间: 2024-10-07 18:08:03