無腦spfa
B. Two Buttons time limit per test 2 seconds memory limit per test 256 megabytes input standard input output standard outputVasya has found a strange device. On the front panel of a device there are: a red button, a blue button and a display showing some positive integer. After clicking the red button, device multiplies the displayed number by two. After clicking the blue button, device subtracts one from the number on the display. If at some point the number stops being positive, the device breaks down. The display can show arbitrarily large numbers. Initially, the display shows number n.
Bob wants to get number m on the display. What minimum number of clicks he has to make in order to achieve this result?
InputThe first and the only line of the input contains two distinct integers n and m (1?≤?n,?m?≤?104), separated by a space .
OutputPrint a single number — the minimum number of times one needs to push the button required to get the number m out of number n.
Sample test(s) input4 6output
2input
10 1output
9Note
In the first example you need to push the blue button once, and then push the red button once.
In the second example, doubling the number is unnecessary, so we need to push the blue button nine times.
#include#include #include #include #include using namespace std; const int maxn=20020; int n,m; struct Edge { int to,next; }edge[maxn*5]; int Adj[maxn],Size; void init_edge() { Size=0; memset(Adj,-1,sizeof(Adj)); } void Add_Edge(int u,int v) { edge[Size].next=Adj[u]; edge[Size].to=v; Adj[u]=Size++; } int dist[maxn],cQ[maxn]; bool inQ[maxn]; bool spfa() { memset(dist,63,sizeof(dist)); memset(cQ,0,sizeof(cQ)); memset(inQ,false,sizeof(inQ)); dist[n]=0; queue q; inQ[n]=true;q.push(n); cQ[n]=1; while(!q.empty()) { int u=q.front();q.pop(); for(int i=Adj[u];~i;i=edge[i].next) { int v=edge[i].to; if(dist[v]>dist[u]+1) { dist[v]=dist[u]+1; if(!inQ[v]) { inQ[v]=true; cQ[v]++; if(cQ[v]>=maxn) return false; q.push(v); } } } inQ[u]=false; } return true; } int main() { scanf("%d%d",&n,&m); if(n>m) { printf("%d\n",n-m); return 0; } /// build graph init_edge(); for(int i=1;i<=10000;i++) { if(2*i 0) Add_Edge(i,i-1); } spfa(); printf("%d\n",dist[m]); return 0; }