POJ3278_Catch that cow

A simple bfs question.

The purpose of using a structure is to save the number of steps the bfs took when it got here.

Without further ado, on the AC code:

//18:18 
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<queue>
using namespace std;
int n,k;
int step[2]={-1,1};
const int maxn=150005;
int flag[maxn];
struct state{
    int cur;
    int cnt;
};
queue<state> qs;
int bfs(){
    state src,dst;
    src.cnt=0;src.cur=n;
    qs.push(src);
    src.cnt=0;src.cur=n;
    while(qs.empty()==0){
        state now=qs.front();
        qs.pop();
        //printf("%d %d\n",now.cur,now.cnt);
        if(now.cur==k)return now.cnt;
        state next;
        next.cnt=now.cnt+1;
        flag[now.cur]=1;
        for(int i=0;i<2;i++){
            next.cur=now.cur+step[i];
            if(next.cur<0||next.cur>maxn)continue;
            if(flag[next.cur]==0){
                qs.push(next);
            }
        }
        next.cur=now.cur*2;
        if(next.cur<0||next.cur>maxn)continue;
        if(flag[next.cur]==0){
            qs.push(next);
        }
    }
    return -1;
}
int main(void){
    scanf("%d%d",&n,&k);
    memset(flag,0,sizeof(flag));
    printf("%d\n",bfs());
    return 0;
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325016470&siteId=291194637