POJ 3278 Catch That Cow

BFS

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<cstdlib>
#include<queue>
using namespace std;

int N ,K;
typedef pair<int ,int >P;
queue<P>que;
int d[200010];

int bfs()
{
    int time=0;
    P p;
    p.first=N;
    p.second=0;
    que.push(p);
    d[N]=1;
    while(que.size())
    {
        p=que.front();
        que.pop();
        P t1,t2,t3;
        t1.first=p.first+1;
        t2.first=p.first-1;
        t3.first=p.first*2;
        t1.second=t2.second=t3.second=p.second+1;
        if(t1.first==K || t2.first==K || t3.first==K )
            return p.second+1;
        if(t1.first<=K && !d[t1.first])
        {
            que.push(t1);
            d[t1.first]=1;
        }
        if(t2.first<=K &&!d[t2.first])
        {
            que.push(t2);
            d[t2.first]=1;
        }
        if(t3.first<=K*2 && !d[t3.first])
        {
            que.push(t3);
            d[t3.first]=1;
        }
    }
}

void fun()
{
    while(que.size())
        que.pop();
}
int main()
{
    while(scanf("%d%d",&N,&K)!=EOF)
    {
        memset(d,0,sizeof(d));

        if(N>=K)
            printf("%d\n",N-K);
        else{
        fun();
        printf("%d\n",bfs());}
    }
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值