POJ3278-Catch That Cow

題目鏈接:POJ3278

一個細節。int 類型的函數要寫return 0;不寫的話會錯好多遍,比如我……

對於n>k由於只有一種走法,所以直接n-k就好了,不然會T,這種情況要特判一下。

AC代碼:

#include<stdio.h>
#include<queue>
#include<string.h>
using namespace std;
const int maxn=1e5+10;
bool vis[maxn];
int n,k;
struct node{
    int loc;
    int step;
};
int bfs(int s){
    queue<node> q;
    memset(vis,false,sizeof(vis));
    node a;
    a.loc=s;
    a.step=0;
    vis[s]=true;
    q.push(a);
    while(!q.empty()){
        node cur=q.front();
        q.pop();
        if(cur.loc==k){
            return cur.step;
        }
        int cx=cur.loc;
        int cs=cur.step;
        if(cx*2<=1e5&&!vis[cx*2]){
            node t;
            t.loc=cx*2;
            t.step=cs+1;
            vis[cx*2]=1;
            q.push(t);
        }
        if(cx+1<=1e5&&!vis[cx+1]){
            node t;
            t.loc=cx+1;
            t.step=cs+1;
            vis[cx+1]=1;
            q.push(t);
        }
        if(cx-1<=1e5&&cx-1>=0&&!vis[cx-1]){
            node t;
            t.loc=cx-1;
            t.step=cs+1;
            vis[cx-1]=1;
            q.push(t);
        }
    }
    return 0;//不寫這句話 wa 了幾百遍
}
int main(){
    scanf("%d%d",&n,&k);
    if(n>k) printf("%d\n",n-k);
    else{
        printf("%d\n",bfs(n));
    }
    return 0;

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章