`
huobengluantiao8
  • 浏览: 1032903 次
文章分类
社区版块
存档分类
最新评论

POJ 3278 Catch That Cow bfs

 
阅读更多

来源:http://poj.org/problem?id=3278

题意:给一个开始点和一个结束点,求从开始点到结束点需要多少步。可以左走一步,右走一步,或者坐标乘2.

思路:裸的bfs啊,水题一枚。

代码:

#include <iostream>
#include <cstdio>
#include <queue>
#include <string.h>
using namespace std;

#define CLR(arr,val) memset(arr,val,sizeof(arr))
const int N = 100000;
int flag[N];
struct point{
	int num,cnt;
}pp[N+5];
int bfs(int begin,int end){
	queue<int> qq;
	CLR(flag,0);
	qq.push(begin);
	flag[begin] = 1;
	pp[begin].cnt = 0;
	while(1){
		int x = qq.front();
		qq.pop();
		//printf("x = %d\n",x);
		if(x == end)
			break;
		if(x - 1 >= 0 && x - 1 <= N && !flag[x-1]){
			qq.push(x-1);
			flag[x-1] = true;
			pp[x-1].cnt = pp[x].cnt + 1;
		}
		if(x+1 >= 0 && x+1 <= N && !flag[x+1]){
			qq.push(x+1);
			flag[x+1] = true;
			pp[x+1].cnt = pp[x].cnt + 1;
		}
		if(2 * x >= 0 && 2 * x <= N && !flag[2*x]){
			qq.push(2*x);
			flag[2*x] = true;
			pp[2*x].cnt = pp[x].cnt + 1;
		}
	}
	return pp[end].cnt;
}
int main(){
	int begin,end;
	while(scanf("%d%d",&begin,&end) != EOF){
	    int x = bfs(begin,end);
		printf("%d\n",x);
	}
	return 0;
}


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics