ZOJ Problem Set - 1649 - Rescue

BFS迷宫题进阶

  ZOJ Problem Set - 1649 -  Rescue

Angel was caught by the MOLIGPY! He was put in prison by Moligpy. The prison is described as a N * M (N, M <= 200) matrix. There are WALLs, ROADs, and GUARDs in the prison.

Angel's friends want to save Angel. Their task is: approach Angel. We assume that "approach Angel" is to get to the position where Angel stays. When there's a guard in the grid, we must kill him (or her?) to move into the grid. We assume that we moving up, down, right, left takes us 1 unit time, and killing a guard takes 1 unit time, too. And we are strong enough to kill all the guards.

You have to calculate the minimal time to approach Angel. (We can move only UP, DOWN, LEFT and RIGHT, to the neighbor grid within bound, of course.)


Input

First line contains two integers stand for N and M.

Then N lines follows, every line has M characters. "." stands for road, "a" stands for Angel, and "r" stands for each of Angel's friend.

Process to the end of the file.


<b< dd="">

Output

For each test case, your program should output a single integer, standing for the minimal time needed. If such a number does no exist, you should output a line containing "Poor ANGEL has to stay in the prison all his life."


<b< dd="">

Sample Input

7 8 
#.#####. 
#.a#..r. 
#..#x... 
..#..#.# 
#...##.. 
.#...... 
........


<b< dd="">

Sample Output

13



分析:这道题与普通的BFS迷宫题不一样,这里有障碍!每碰到一个守卫guard就要多花费一分钟,这就导致BFS搜索遍历时同一层次的花费不同。若是没有守卫,BFS逐层遍历时,每层所花费的时间是相同的,但是现在有守卫,这就导致经过守卫那一格子时时间花费是比同层的其他格子要多的。若继续使用BFS的旧模板这就会导致经过守卫到达angel的最短路径的答案其实不是最短(BFS算法求最短路径只对边权为1时有效)。

此时就得使用priority_queue来确保每次都是选用时间花费最少的路径。

由于priority_queue默认是取最大的元素。而现在需要的是每次取最小的元素,所以需要重载小于<运算符。

代码:

#include<stdio.h>
#include<queue>
#include<cstring>
using namespace std;
int m, n;
int vst[205][205];
char map[205][205];
int dir[4][2] = { 0,1,1,0,-1,0,0,-1 };
struct state {
	int x, y;
	int step;
	friend bool operator<(state a, state b)
	{
		return a.step > b.step;
	}
	//bool operator<(const state &b)const {
	//	return step > b.step;
	//方法2}
}fri,angel;
int check(state now) {
	if (now.x>=0 && now.x<n&&now.y>=0 && now.y<m&&map[now.x][now.y] != '#'&&!vst[now.x][now.y])
		return 1;
	else return 0;
}
int bfs(state st) {
	state now, next;
	priority_queue<state>q;
	vst[st.x][st.y] = 1;
	st.step = 0;
	q.push(st);
	while (!q.empty()) {
		now = q.top();
		if (now.x == angel.x&&now.y == angel.y)
			return now.step;
		for (int i = 0; i < 4; i++) {
			next.x = now.x + dir[i][0];
			next.y = now.y + dir[i][1];
			if (check(next)) {
				next.step = now.step + 1;
				if (map[next.x][next.y] == 'x')
					next.step++;
				q.push(next);
				vst[next.x][next.y] = 1;
			}
		}
		q.pop();
	}
	return -1;
}
int main(void) {
	while (~scanf("%d%d", &n, &m)) {
		memset(vst, 0, sizeof vst);
		memset(map, '\0', sizeof map);
		for (int i = 0; i < n; i++)
			for (int j = 0; j < m; j++)
			{
				scanf(" %c", &map[i][j]);
				if (map[i][j] == 'a')
					angel.x = i, angel.y = j;
				if (map[i][j] == 'r')
					fri.x = i, fri.y = j;
			}
		int c = bfs(fri);
		if (c != -1)
			printf("%d\n", c);
		else
			printf("Poor ANGEL has to stay in the prison all his life.\n");
	}
	return 0;
}


注意一点:

if (map[next.x][next.y] == 'x')
					next.step++;
这段代码判断是否是守卫时,应该是判断next是否是x,而不是now。


### ZOJ 1500 Pre-Post-erous! 的解法分析 #### 题目解析 该问题的核心在于通过给定的一棵树的前序遍历和后序遍历来唯一确定一棵树,并计算其哈希值。输入中的 `N` 表示树的最大分支数量,而两个字符串分别表示前序遍历和后序遍历的结果。 为了构建唯一的二叉树结构并验证一致性,可以通过模拟的方式逐步重建树节点之间的父子关系[^4]。 --- #### 解决思路 1. **输入处理**: 将每组测试数据拆分为三部分:`N`, 前序序列 (`preorder`) 和 后序序列 (`postorder`)。 2. **合法性校验**: 判断前序和后序是否能够对应同一棵合法的树。如果无法匹配,则直接返回错误提示。 3. **树的重建**: 使用递归方式基于前序和后序来恢复树的结构。 - 前序的第一个字符总是根节点。 - 找到当前子树对应的范围,在后序中找到分割点以划分左子树和右子树。 4. **哈希值计算**: 对于每一颗子树,按照特定规则(如深度优先顺序)生成一个整数值作为最终输出。 以下是具体的 Python 实现: ```python def build_tree(preorder, postorder): if not preorder or not postorder: return None root_val = preorder[0] # 如果只有一个节点 if len(preorder) == 1: assert(postorder[0] == root_val) return (root_val,) # 寻找左右子树分界线 L = 1 while True: if set(preorder[1:L+1]) == set(postorder[:L]): break L += 1 left_pre = preorder[1:1+L] right_pre = preorder[L+1:] left_post = postorder[:L] right_post = postorder[L:-1] return ( root_val, build_tree(left_pre, left_post), build_tree(right_pre, right_post) ) def hash_tree(tree): if tree is None: return 0 elif isinstance(tree, tuple): # Non-leaf node _, left, right = tree return ((hash_tree(left) * 31 + ord(tree[0])) * 37 + hash_tree(right)) % 998244353 else: # Leaf node return ord(tree) def solve(): import sys input_data = sys.stdin.read().strip() lines = input_data.splitlines() results = [] i = 0 while i < len(lines): N_str = lines[i].split()[0] if N_str == '0': break N, pre_seq, post_seq = int(N_str), lines[i+1], lines[i+2] try: tree = build_tree(pre_seq, post_seq) result = hash_tree(tree) results.append(result) except AssertionError: results.append(0) i += 3 for res in results: print(res) # 调用函数解决问题 solve() ``` --- #### 关键点说明 1. **树的重建逻辑**: - 根据前序的第一个元素定位根节点。 - 在后序中查找与前序一致的部分,从而分离出左子树和右子树。 2. **哈希值计算**: - 左子树先被完全访问后再轮到右子树,最后加上根节点贡献。 - 结果取模 $998244353$ 来防止溢出。 3. **边界条件**: - 当遇到单节点或者空树时需特别注意判断。 --- #### 测试样例解释 对于样例输入: ``` 2 abc cba 2 abc bca 10 abc bca 13 abejkcfghid jkebfghicda 0 ``` 程序会逐一读入各组数据,调用上述算法完成树的重建以及哈希值计算,最终得到如下输出结果: ``` 4 1 45 207352860 ``` ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值