POJ.3278 Catch That Cow (BFS)

来源:互联网 发布:邮箱服务器地址和端口 编辑:程序博客网 时间:2024/06/04 19:08

POJ.3278 Catch That Cow (BFS)

题意分析

给出给出初始坐标N,你可以执行的操作有N-1,N+1,N*2,求出最少需要几次操作,使得N=K。

BFS时每次有3种操作,按照操作来即可。特别需要注意越界的问题,坐标不能小于0,也不能大于题目给的最大值100000.然后就没太大问题。

一开始因为忘记数组越界的问题,RE了几次。

代码总览

#include <queue>#include <cstdio>#include <algorithm>#include <cstring>#define nmax 100005using namespace std;int sta ,end;typedef struct{    int pos;    int times;}mes;bool visit[nmax];queue<mes> q;void bfs(){    while(!q.empty()) q.pop();    mes temp, head = {sta,0};    q.push(head);    while(!q.empty()){        head = q.front();q.pop();        if(head.pos == end){            printf("%d\n",head.times);            return;        }        temp.times = head.times + 1;        temp.pos = head.pos-1;        if(temp.pos >=0 && !visit[temp.pos]){            q.push(temp);            visit[temp.pos] = true;        }        temp.pos = head.pos+1;        if(temp.pos < nmax && !visit[temp.pos]){            q.push(temp);            visit[temp.pos] = true;        }        temp.pos = head.pos * 2 ;        if(temp.pos < nmax && !visit[temp.pos]){            q.push(temp);            visit[temp.pos] = true;        }    }}int main(){    while(scanf("%d %d",&sta,&end) != EOF){        memset(visit,0,sizeof(visit));        bfs();    }    return 0;}
原创粉丝点击