链接:https://vjudge.net/problem/POJ-3278
题意:
给定n,k。有三种操作n-1,n+1,n*2。
找到从n到k的最少步骤。
思路:
BFS
代码:
#include <iostream> #include <queue> using namespace std; const int MAXN = 1e5+10; struct Node { int _x; int _step; Node(int x,int step) { _x = x; _step = step; } }; int vis[MAXN]; int main() { int n,k; scanf("%d%d",&n,&k); queue<Node> Q; Q.push(Node(n,0)); vis[n] = 1; while (!Q.empty()) { int x = Q.front()._x; int step = Q.front()._step; if (x == k) break; if (x-1 >= 0&&x-1<MAXN&&vis[x-1] == 0) { Q.push(Node(x-1,step+1)); vis[x-1] = 1; } if (x+1 >= 0&&x+1<MAXN&&vis[x+1] == 0) { Q.push(Node(x+1,step+1)); vis[x+1] = 1; } if (x*2 >= 0&&x*2<MAXN&&vis[x*2] == 0) { Q.push(Node(x*2,step+1)); vis[x*2] = 1; } Q.pop(); } printf("%d ",Q.front()._step); return 0; }