HDU 2717(BFS_G题)解题报告

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

-----------------------------------------------------------------------------------

题意:在一个数轴上有n和k,农夫在n,奶牛在k,农夫要抓住奶牛,有两种方法:1、到x+1的位置和x-1的位置。2、到2*x的位置。利用这两种方法,求最小到达时间

思路:bfs,把每次的情况判断一下,最先到达的一定最小。

代码:

#include<iostream>
#include<algorithm>
#include<memory.h>
#include<queue>
using namespace std;
const int MAX=100001;
const int Max=0x3f3f3f3f;
int cow[MAX],n,k;
void bfs()
{
    queue<int> q;
    q.push(n);
    cow[n]=0;
    while(!q.empty()) {
        int cur=q.front();
        q.pop();
        if(cur==k) return;
        int x=cur+1;
        if(x>=0&&x<MAX&&cow[cur]+1<cow[x]) {
            cow[x]=cow[cur]+1;
            q.push(x);
        }
        x=cur-1;
        if(x>=0&&x<MAX&&cow[cur]+1<cow[x]) {
            cow[x]=cow[cur]+1;
            q.push(x);
        }
        x=cur*2;
        if(x>=0&&x<MAX&&cow[cur]+1<cow[x]) {
            cow[x]=cow[cur]+1;
            q.push(x);
        }
    }
}
int main()
{
    while(~scanf("%d%d",&n,&k)) {
        fill(cow,cow+MAX,Max);
        bfs();
        printf("%d\n",cow[k]);
    }
    return 0;
}
View Code

 

posted @ 2018-01-29 15:11  caomp  阅读(158)  评论(0)    收藏  举报