广搜基础 Farmer John

来源:互联网 发布:毕业舞会礼服知乎 编辑:程序博客网 时间:2024/06/02 17:20
<pre name="code" class="cpp">auther:DHtopic:BFS
Sorce:POJ 3278time:2014 7 16#include <iostream></span>#include<cstring>#include<cstdio>#include <queue>using namespace std;#define maxn 100005int main(){    int n , k ;   while(scanf("%d%d",&n,&k)==2)   {    queue<int> q;    q.push (n);    int t[maxn];    bool vis[maxn];   memset(t,0,sizeof(t));   memset(vis,0,sizeof(vis));   if(n==k)printf("0");   else {    while (!q.empty()){        int temp = q.front();        q.pop();        if (temp-1 > -1 &&!vis[temp-1]){            t[temp - 1] = t [temp] + 1;            q.push (temp - 1);vis[temp-1]=1;            if (temp-1 == k ) break;        }        if (temp+1 < maxn&&!vis[temp+1]){            t[temp + 1] = t [temp] + 1;            q.push (temp + 1);vis[temp+1]=1;            if (temp+1 == k ) break;        }        if (2*temp < maxn&& !vis[2*temp])        {            t[2*temp] = t [temp] + 1;            q.push (2*temp);vis[2*temp]=1;            if (2*temp == k ) break;        }    }    printf("%d\n",t[k]);    }    }    return 0;}


                                             
0 0
原创粉丝点击