程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> 關於C++ >> Codeforces 520B. Two Buttons spfa

Codeforces 520B. Two Buttons spfa

編輯:關於C++


無腦spfa

B. Two Buttons time limit per test 2 seconds memory limit per test 256 megabytes input standard input output standard output

Vasya 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?

Input

The first and the only line of the input contains two distinct integers n and m (1?≤?n,?m?≤?104), separated by a space .

Output

Print 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) input
4 6
output
2
input
10 1
output
9
Note

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*i0) Add_Edge(i,i-1);
    }
    spfa();
    printf("%d\n",dist[m]);
    return 0;
}




  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved