解救小哈 - BFS 版本讲解
- 使用队列存储到达过的点,对队列中的每一个点再向四个方向拓展。
- 最优性:最近的点会最早进入队列
程序填空:
1from collections import deque2q = deque()3n, m, t = map(int, input().split())4sx, sy, tx, ty = map(int, input().split())5a = [[0 for _ in range(m + 1)] for _ in range(n + 1)]6step = [[-1 for _ in range(m + 1)] for _ in range(n + 1)]7for _ in range(t):8 x, y = map(int, input().split())9 a[x][y] = 110
11def ok(x, y):12 return 1 <= x <= n and 1 <= y <= m and a[x][y] == 0 and step[x][y] == -113
14d = ((0, 1), (0, -1), (1, 0), (-1, 0))15q.append((sx, sy))10 collapsed lines
16step[sx][sy] = 017while len(q) > 0:18 x, y = q.popleft()19 for i in range(4):20 nx, ny = x + d[i][0], y + d[i][1]21 if ok(nx, ny):22 q.append((nx, ny))23 step[nx][ny] = step[x][y] + 124
25print(step[tx][ty])
13 3 221 1 3 132 142 2
Leaders
https://usaco.org/index.php?page=viewproblem2&cpid=1275
观察规律:若 G + H 组合,则 H 必须包含后面全部 H,且前面的 G 是第一个且包含全部 G,或 G 包含此 H。判断时,使用最早出现的 H 和 G 判断
1n = int(input())2s = input()3p = list(map(int, input().split()))4p = [(x - 1) for x in p]5fh, fg = -1, -16lh, lg = -1, -17for i in range(n):8 if s[i] == 'H':9 lh = i10 if fh == -1:11 fh = i12 else:13 lg = i14 if fg == -1:15 fg = i11 collapsed lines
16ans = 017# GGHH ; G + H 必须 H 包含所有 H18if p[fh] >= lh: # fh and some g before that19 for i in range(fh):20 if p[i] >= fh or (i == 0 and p[i] >= lg):21 ans += 122if p[fg] >= lg:23 for i in range(fg):24 if p[i] >= fg or (i == 0 and p[i] >= lh):25 ans += 126print(ans)
1n = int(input())2s = input()3p = list(map(int, input().split()))4p = [___ for x in p]5fh, fg = -1, -16lh, lg = -1, -17for i in range(n):8 if s[i] == 'H':9 ___10 if fh == -1:11 ___12 else:13 ___14 if fg == -1:15 ___11 collapsed lines
16ans = 017# GGHH ; G + H 必须 H 包含所有 H18if p[fh] >= lh: # fh and some g before that19 for i in range(fh):20 if ___21 ans += 122if p[fg] >= lg:23 for i in range(fg):24 if p[i] >= fg or (i == 0 and p[i] >= lh):25 ans += 126print(ans)
# P2385 [USACO07FEB] Bronze Lilypad Pond B
经典的 bfs 题目,但此题每个拓展点有八个方向进行选择,类似于象棋马步
1创建空队列2将起点放入队列3while 队列不空:4 取出并弹出队首 u5 将 u 的八个方向判断是否在边界内且为莲花或终点6 将可行且没走过的点加入队列7输出终点距离8
9python deque:10push: d.append(4) / a.appendleft(4)11front: d[0]12pop: d.popleft() / d.pop()