BFS/acm習題集

wulurula發表於2020-11-22

A - Catch That Cow

// 沒有什麼坑~~

#include <iostream>
#include <string>
#include <string.h>
#include <algorithm>
#include <queue>
#define MAX 900100
#define INF 99999999
using namespace std;
struct node
{
    int num,step;
    node(int n,int s)
    {
        num = n;
        step = s;
    }
};
bool vis[MAX];
int main()
{
    int N,K;
    while(~scanf("%d%d",&N,&K))
    {
        int x,ans;
        queue<node> q;
        q.push(node(N,0));
        memset(vis,false,sizeof(vis));
        vis[N] = 1;

        while(!q.empty())
        {
            node tmp = q.front();
            q.pop();
            x = tmp.num;
            ans = tmp.step;
            if(x == K)
            {
                break;
            }
            if(x>0 && vis[x-1]==0) //分三種情況
            {
                q.push(node(x-1,ans+1));
                vis[x-1] = 1;
            }
            if(x<=K && vis[x+1]==0)
            {
                q.push(node(x+1,ans+1));
                vis[x+1] = 1;
            }
            if(x<=K && vis[2*x]==0)
            {
                q.push(node(2*x,ans+1));  //記得開兩倍大小
                vis[2*x] = 1;
            }
        }
        cout<<ans<<endl;
    }
    return 0;
}

相關文章