ํ‹ฐ์Šคํ† ๋ฆฌ ๋ทฐ

728x90

๐Ÿšฉ ํŠธ๋ฆฌ(tree)

์ฝ”๋“œ

T = int(input())

def size(root):
    global cnt
    if tree[root][0]:
        cnt += 1
        size(tree[root][0])
    if tree[root][1]:
        cnt += 1
        size(tree[root][1])

for tc in range(1, T+1):
    E, N = map(int, input().split())  # ๊ฐ„์„ ๊ฐœ์ˆ˜, root
    tmp = list(map(int, input().split()))  # ๋ถ€๋ชจ-์ž์‹
    tree = [[0] * 3 for _ in range(E+2)]
    for i in range(E):
        # [์™ผ์ชฝ์ž์‹, ์˜ค๋ฅธ์ชฝ์ž์‹, ๋ถ€๋ชจ๋…ธ๋“œ]
        parent, child = tmp[i * 2], tmp[i * 2 + 1]
        tree[child][2] = parent
        if not tree[parent][0]:
            tree[parent][0] = child
        else:
            tree[parent][1] = child

    cnt = 1
    size(N)
    print("#{} {}".format(tc, cnt))
๋Œ“๊ธ€