Fluency: Written Test (20190911)

Posted by dman779 on Thu, 03 Oct 2019 15:50:35 +0200

Gift distribution

The idea of dynamic programming. Consider three possibilities. There are no right ones on the left, right ones on the left, left ones on the left and right ones on the right. There are two kinds of cases: left side and right side, that is, left side or right side.

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
'''

The cat catches mice.

A typical breadth-first traversal topic. First, find the starting point, set up a double ended queue, and add one layer to each time until the final result is found, that is, the target value is equal to 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
'''

(Recent update: 14 September 2019)

Topics: Programming