#include<iostream> #include<cstdio> #include<cstring> #include<queue> using namespace std; const int maxn = 10010; const int inf = 0x7fffffff; int vis[maxn*10] ; int n,m;int ans = inf; struct node { int step ; int value ; }; struct cmp{ bool operator()(struct node &a,struct node &b) { return a.step>b.step; } }; void bfs() { priority_queue<struct node,vector<struct node>,cmp> que; struct node first = {0,n}; que.push(first); vis[n] = 1; vis[0] = 1; while(que.size()) { struct node now = que.top(); que.pop(); if(now.value == m) { printf("%d\n",now.step); break; } if((2*now.value >= 0) && (2*now.value <= max(2*n,2*m)) &&(!vis[now.value*2])) { struct node next = {now.step+1,now.value*2}; vis[now.value*2] = 1; que.push(next); } if(now.value - 1 >= 0 && now.value - 1 <= max(2*n , 2*m) && !vis[now.value - 1]) { struct node next = {now.step+1,now.value-1}; vis[now.value-1] = 1; que.push(next) ; } } } int main() { scanf("%d%d",&n,&m); memset(vis,0,sizeof(vis)); bfs(); return 0; }
CodeForces 520B Two Buttons bfs+优先队列
原文:http://blog.csdn.net/cq_pf/article/details/44628795