POJ-3278 && HDU-2717 Catch That Cow 线性BFS题目

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2717
题目大意是:在一条坐标轴上,从一个点到另一个点的最小移动步数,移动方法有两种,一是向左走一步或是向右走一步,二是瞬移到当前坐标的二倍处。
解题思路:因为题目询问的是最短步数,且有三种走的方法,所以很直接就想到用BFS来实现。

具体代码如下:

#include <iostream>  
#include <cstdio>  
#include <queue>  
#include <cstring>  
using namespace std; 
const int lim=100005;    
int dirx[2]={1,-1};
int flag[lim]; 
int N,K; 
struct point  
{  
    int x;  
    int step;  
};  
void bfs(); 
bool judge(point p)
{
    if(p.x<0 || p.x>100000 || p.step>flag[p.x])//注意一定要进行边界判断
    {
        return false;
    }
    return true;
}

int main ()  
{  
    //freopen("input.txt", "r", stdin);  
    //freopen("output.txt", "w", stdout);  
    while(~scanf("%d%d",&N,&K))
    {
        if(N==K)
         {
            cout<<0<<endl;
            continue ;
         } 
        memset(flag,0X7F, sizeof(flag));  //
        bfs();  

    }
        return 0; 
}  

void bfs()  
{  
    int i;   
    point node, t;  
        flag[N]=0;
    node.x=N;   
    node.step=0;
    queue<point> q;  
    while(!q.empty())//重要! 
    {
        q.pop();
    }
    q.push(node);  
    while(!q.empty())
    {  

        node=q.front();  
        q.pop();  

        for(i=0; i<3; i++)  
        {  
            t=node;
            if(i==2)
            {
               t.x*=2;
            }
            else
            {
                t.x+=dirx[i];
            }
            t.step=node.step+1;
            if(!judge(t))continue;
            if(t.x==K)  
            {  

                    cout<<t.step<<endl;
                    return ;
                     //第一个到达的即为最小值;

            } 
            flag[t.x]=t.step; 
            q.push(t);  
        }  
    }  
}

仅代表个人观点,欢迎交流探讨,勿喷~~~

这里写图片描述

PhotoBy:WLOP

http://weibo.com/wlop

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值