POJ 3278 Catch That Cow

来源:互联网 发布:ubuntu在线安装jdk1.8 编辑:程序博客网 时间:2024/05/10 23:28

这是一道经典的bfs的题目,由于今天正在学习优先队列所以用优先队列做的,感觉真的很好用啊!赞一个啊!!!

#include <stdio.h>#include <string.h>#include <queue>#include <iostream>#define MAXN 1000004using namespace std;queue<int> x;bool v[MAXN];int step[MAXN];int bfs(int n, int m){    int head, next;    x.push(n);    v[n] = true;    step[n] = 0;    while(!x.empty())    {        head = x.front();        x.pop();        for(int i = 1; i <= 3; i++)        {            if(i == 1)                next = head-1;            else if(i == 2)                next = head+1;            else                next = head*2;            if(next > MAXN-1 || next < 0)//一开始这是没写-1,就是各种RE啊、、后来改掉了就AC了啊、、考录不周啊、、                continue;            if(!v[next])            {                x.push(next);                step[next] = step[head]+1;                v[next] = true;            }            if(next == m)                return step[next];        }    }}int main(){    int n, m;    scanf("%d %d",&n, &m);    if(n >= m)        printf("%d\n",n-m);    else        printf("%d\n",bfs(n,m));    return 0;}