poj 3728 Catch That Cow bfs搜索 坑点在开两倍数组

来源:互联网 发布:电影资源知乎 编辑:程序博客网 时间:2024/06/06 00:19
#include<iostream>#include<cstring>#include<cstdio>#include<queue>using namespace std;bool vis[200100];struct node{int loc;int step;};int main(){int n,k;while(scanf("%d%d",&n,&k)==2){memset(vis,0,sizeof(vis));int ans=0;queue<node> q;node start;start.loc=n;start.step=0;q.push(start);vis[n]=1;while(!q.empty()){node tmp=q.front();q.pop();if(tmp.loc==k){printf("%d\n",tmp.step);break ;}node next1=tmp;next1.loc--;next1.step++;if(next1.loc>=0 && !vis[next1.loc]){q.push(next1);vis[next1.loc]=1; } node next2=tmp;next2.loc++;next2.step++;if(next2.loc>=0 && next2.loc<k*2 && !vis[next2.loc]){q.push(next2);vis[next2.loc]=1;} node next3=tmp;next3.loc*=2;next3.step++;if(next3.loc>=0 && next3.loc<k*2 && !vis[next3.loc]){q.push(next3);vis[next3.loc]=1;} //if(tmp.loc>=1 && !vis[tmp.loc-1])//{//node next;//next.loc=tmp.loc-1;//vis[next.loc]=1;//next.step=tmp.step+1;//q.push(next);//}//if(tmp.loc<=k && !vis[tmp.loc+1])//{//node next;//next.loc=tmp.loc+1;//vis[next.loc]=1;//next.step=tmp.step+1;//q.push(next);//}//if(tmp.loc<=k && !vis[tmp.loc*2])//{//node next;//next.loc=tmp.loc*2;//vis[next.loc]=1;//next.step=tmp.step+1;//q.push(next);//}}}}


为什么开两倍 因为可能往回走 考虑边界条件 就能想出