int n, k,ans;
bool vis[N];
struct node {
int w, len;
};
void bfs()
{
queue<node> q;
q.push(node{n,0});vis[n] = true;
while (!q.empty())
{
node now = q.front();q.pop();
if (now.w == k) { ans = now.len;return; }
if (!vis[now.w + 1] && now.w + 1 <= k) { q.push(node{ now.w + 1,now.len + 1 });vis[now.w + 1] = true;; }
if (!vis[now.w - 1] && now.w - 1 >=0) { q.push(node{ now.w - 1,now.len + 1 });vis[now.w - 1]=true; }
if (!vis[now.w * 2] && now.w < k) { q.push(node{ now.w * 2,now.len + 1 });vis[now.w * 2]=true; }
}
}
int main()
{
while (cin >> n >> k)
{
ans == 0;
if (n == k) { puts("0");continue; }
bfs();
cout << ans << endl;
}
return 0;
}
Catch That Cow POJ - 3278(拓展出边)
最新推荐文章于 2020-05-13 22:58:15 发布