礼物派发
动态规划的思想。考虑三种可能,左边没有右边有,左边有右边没有,左边有和右边有。其中左边有和右边有则分两种情况,即加入左边或者加入右边。
def send_gift(n, a, b, seq):
if n == 0:
return 0
if not seq:
return 0
left, right = seq[0]
first, second, third = float('inf'), float('inf'), float('inf')
# print(left, right, a, b)
if a < 1 and b > 0:
first = right + send_gift(n - 1, a, b - 1, seq[1:])
if b < 1 and a > 0:
second = left+send_gift(n-1, a-1, b, seq[1:])
if a > 0 and b > 0:
third = min(left+send_gift(n-1, a-1, b, seq[1:]),
right + send_gift(n - 1, a, b - 1, seq[1:]))
return min(first, second, third)
if __name__ == '__main__':
n = int(input().strip())
a, b = list(map(int, input().strip().split()))
seq = []
for _ in range(n):
cur = list(map(int, input().strip().split()))
seq.append(cur)
res = send_gift(n, a, b, seq)
print(res)
'''
3
1 2
13 19
4 9
10 20
'''
猫捉老鼠
典型的一道广度优先遍历的题目。先找到起点,设置一个双端队列,每一次都往外递增一层,直到找到最终的结果,即目标值等于3的位置。
import sys
from collections import deque
def cat_catch_mouse(seq):
if not seq:
return 0
row, col = len(seq), len(seq[0])
start = find_point(seq, row, col)
container = deque()
container.append([start])
res = -1
while container:
value = container.popleft()
res += 1
current = set()
# print(container, value, res)
for vu in value:
r, c = vu
if seq[r][c] == 3:
return res
if r-1 >= 0 and seq[r-1][c] != 1:
current.add((r-1, c))
if r+1 < row and seq[r+1][c] != 1:
current.add((r+1, c))
if c-1 >= 0 and seq[r][c-1] != 1:
current.add((r, c-1))
if c+1 < col and seq[r][c+1] != 1:
current.add((r, c+1))
container.append(list(current))
def find_point(seq, row, col):
for si in range(row):
for sj in range(col):
if seq[si][sj] == 2:
return (si, sj)
if __name__ == '__main__':
seq = []
for line in sys.stdin:
seq.append(list(map(int, line.strip().split())))
res = cat_catch_mouse(seq)
print(res)
'''
2 0 0 1
0 1 0 1
1 0 0 0
3 0 1 0
'''
(最近更新:2019年09月14日)