POJ3278 (2) 双向BFS

#include<stdio.h>

#define MAX_N 100000
#define MAX_INT 0x7fffffff //32位

int frontQueue[MAX_N+2], rearQueue[MAX_N+2]; // 前后队列
int location[MAX_N+2]; 

void init(){
	int i;
	for(i = 0; i <= MAX_N; i++) {
		frontQueue[i] = -2;
		rearQueue[i] = -2;
		location[i] = MAX_INT;
	}
}

int getNextFromFront(int loc , int which) {
	if(which == 0) {
		return loc-1;
	}else if(which == 1) {
		return loc+1;
	}else if(which == 2) {
		return loc*2;
	}
	return -1;
}

int getNextFromRear(int loc, int which) {
	if(which == 0) {
		return loc-1;
	}else if(which == 1) {
		return loc+1;
	}else if(which == 2 && ( loc%2 == 0)) { //注意是能被2整除,和乘以二相反
		return loc /2;
	}
	return -1;
}

int getMinTime(int start , int target){
	int step = 0;
	int nextLoc, end, j;

	int fromIndex1 = 0 , fromIndex2 = 0, toIndex1 = 0, toIndex2 = 0;
	int currIndex;

	if(start >= target) 
		return start - target;

	location[start] = 0;
	location[target] = -1;
	frontQueue[toIndex1] = start;  // 起点
	rearQueue[toIndex2] = target; // 终点

	// 前向找到时,直接输出;  否则前向和后向相交时,返回结果为相交点上,前后走过步数之和
	while(fromIndex1 <= toIndex1 && fromIndex2 <=toIndex2) {
		step++; // 记录步数
		end = toIndex1; //结束点
		for(currIndex = fromIndex1; currIndex <= end; currIndex++) {
			for(j = 0; j < 3; j ++) {
				nextLoc = getNextFromFront(frontQueue[currIndex], j);
				if(nextLoc == target) return step; //直接找到
				if(nextLoc > MAX_N || nextLoc <0) continue;
				if(location[nextLoc] == MAX_INT) {
					location[nextLoc] = step;
					frontQueue[++toIndex1] = nextLoc; // 放入队列
				}else if(location[nextLoc] < 0) { // 和后向队列相交
					return step - location[nextLoc];
				}
			}
		}
		fromIndex1 = end + 1; // 更新下一次开始点为上一次结束点的下一个

		end = toIndex2;
		for(currIndex = fromIndex2; currIndex <= end; currIndex++) {
			for(j = 0; j < 3; j ++) {
				nextLoc = getNextFromRear(rearQueue[currIndex], j);
				if(nextLoc > MAX_N || nextLoc <0) continue;
				if(location[nextLoc] == MAX_INT) {
					location[nextLoc] = -step; // 注意是-step
					rearQueue[++toIndex2] = nextLoc;
				}else if(location[nextLoc] >= 0) {
					return step + location[nextLoc];// 和前向队列相交
				}
			}
		}
		fromIndex2 = end + 1;
	}
	
	return -1;
}

int main(){
	int start , target;

	freopen("input.txt", "r", stdin);
	scanf("%d %d", &start, &target);

	init();
	printf("%d\n", getMinTime(start, target));
	return 0;
}

2018 03 08更新

学习下双向BFS, 直接上代码。。






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值