当前位置: 代码迷 >> 综合 >> POJ 3278 Catch That Cow (队列+bfs)
  详细解决方案

POJ 3278 Catch That Cow (队列+bfs)

热度:93   发布时间:2023-11-06 18:53:25.0

题意:

给出农夫和牛的位置,求农夫抓到牛的最短时间,农夫可以选择前进一步,后退一步,当前位置坐标变成两倍。每做出一次选择都要花费一秒、

思路:

以前是用数组做的,现在重新用队列做了一遍,vis标记的时候=打成==,结果死循环。

#include<iostream>
#include<cstdio>
#include<queue> 
#include<cstring>
#define mx 100000
using namespace std;struct aa{int x,bu;aa(int x_=0,int bu_=0){x=x_;bu=bu_;}};queue<aa>q;int st,en,vis[100010];int  bfs(int st){aa now;q.push(aa(st,0));vis[st]=1;while(!q.empty()){now=q.front();q.pop();int x=now.x;if(x==en) return now.bu;if(x<en){if(x-1>=0&&vis[x-1]==0){//	cout<<"后退"<<endl; vis[x-1]=1;q.push(aa(x-1,now.bu+1)); }if(x+1<=mx&&vis[x+1]==0){//youhua//	cout<<"前进"<<endl; vis[x+1]=1;q.push(aa(x+1,now.bu+1)); }if(2*x<=mx&&vis[2*x]==0){//	cout<<"两倍"<<endl; vis[2*x]=1;	q.push(aa(2*x,now.bu+1)); }}else{if(x-1>=0&&vis[x-1]==0){//		cout<<"过头后退"<<endl; vis[x-1]=1;q.push(aa(x-1,now.bu+1)); }}}}int main(){while(scanf("%d%d",&st,&en)!=EOF){if(!q.empty()) q.pop();memset(vis,0,sizeof(vis));printf("%d\n",bfs(st));}return 0;}