HDU 2717 Catch That Cow(bfs基础)

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2717

题意:在一维坐标轴上给你起点和终点的坐标,你可以向前走一步向后走一步移动到当前坐标*2的点 ,问你最少能用几步到达终点

思路:其实我一开始想用dfs的,后来做不出来,看到网上的blog都是用bfs,唉。。。。

AC代码:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
int m,k;
int vis[200000];
struct node{
    int x;
    int step;
}q,temp;
int  bfs()
{
    int i;
    memset(vis,0,sizeof(vis));
    queue<node>que;
    que.push(q);
    vis[q.x]=1;
    while(!que.empty())    
    {
        q=que.front();
        que.pop();
        if(q.x==k) return q.step;
        temp=q;
        temp.x=q.x+1;
        if(temp.x>=0&&temp.x<=100000&&vis[temp.x]==0)
        {
            temp.step=q.step+1;
            vis[temp.x]=1;
            que.push(temp);
        }
        temp.x=q.x-1;
        if(temp.x>=0&&temp.x<=100000&&vis[temp.x]==0)
        {
            temp.step=q.step+1;
            vis[temp.x]=1;
            que.push(temp);
        }
        temp.x=q.x*2;
        if(temp.x>=0&&temp.x<=100000&&vis[temp.x]==0)
        {
            temp.step=q.step+1;
            vis[temp.x]=1;
            que.push(temp);
        }
    }
}
int main()
{
    while(scanf("%d%d",&m,&k)!=EOF)
    {
        q.x=m;
        q.step=0;
        cout<<bfs()<<endl;
    }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值