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

728x90

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

 

thinking

[๋ถ€๋ชจ๋…ธ๋“œ, ์™ผ์ชฝ์ž์‹, ์˜ค๋ฅธ์ชฝ์ž์‹, ๋…ธ๋“œ๊ฐ’] ์˜ 2์ฐจ์› ๋ฆฌ์ŠคํŠธ ํ˜•ํƒœ์˜ ํŠธ๋ฆฌ๋ฅผ ๋งŒ๋“ค๊ณ  input data ๊ฐ’์„ ๋„ฃ์–ด์ค€๋‹ค.

์™ผ์ชฝ์ž์‹, ์˜ค๋ฅธ์ชฝ์ž์‹์˜ ๋…ธ๋“œ๋ฒˆํ˜ธ๊ฐ€ 1์”ฉ ์ฐจ์ด๋‚˜๋ฏ€๋กœ ์ธ๋ฑ์Šค๋ฅผ ํ™€์ง์œผ๋กœ ์ ‘๊ทผํ•ด ๊ฐ’์„ ๋„ฃ์–ด์คฌ๊ณ ,

๋งŒ์•ฝ ์ „์ฒด ๋…ธ๋“œ์˜ ๊ฐœ์ˆ˜๊ฐ€ ์ง์ˆ˜์ธ ๊ฒฝ์šฐ ์˜ค๋ฅธ์ชฝ ์ž์‹์ด ์—†์œผ๋ฏ€๋กœ 0์œผ๋กœ ๋‹ค์‹œ ํ• ๋‹นํ•ด์ฃผ๋Š” ์กฐ๊ฑด๋ฌธ์„ ์„ค์ •ํ–ˆ๋‹ค.

change ๋ผ๋Š” ํ•จ์ˆ˜๋ฅผ ํ†ตํ•ด ๋ถ€๋ชจ<์ž์‹์ด ๋˜๋„๋ก ๋ฐ”๊ฟ”์ฃผ๋Š”๋ฐ, ์žฌ๊ท€์ ์œผ๋กœ ์ ‘๊ทผํ•˜์ง€ ์•Š์„ ๊ฒฝ์šฐ

๋งŒ์•ฝ 5-3-1์˜ ๊ฒฝ์šฐ๋ผ๋ฉด ํ•จ์ˆ˜ 1๋ฒˆ ์‹œํ–‰์‹œ์— 3-5-1, ํ•จ์ˆ˜ 2๋ฒˆ ์‹œํ–‰์‹œ์— 3-1-5๊ฐ€ ๋˜์–ด

์ „์ฒด์ ์œผ๋กœ ๋ดค์„ ๋•Œ ๋ถ€๋ชจ<์ž์‹์ด ํ•ญ์ƒ ์„ฑ๋ฆฝํ•˜์ง€ ์•Š๊ฒŒ ๋œ๋‹ค.

(์ฒ˜์Œ ์ฝ”๋“œ๋ฅผ ์ž‘์„ฑํ–ˆ์„ ๋•Œ ์žฌ๊ท€๋กœ ๊ตฌ์„ฑํ•˜์ง€ ์•Š์•„ 9๊ฐœ์˜ testcase ์ค‘ 3๊ฐœ๋งŒ ๋งž์•˜๋‹ค.)

์žฌ๊ท€๋กœ ๋ถ€๋ชจ<์ž์‹์ด ๋ ๋•Œ๊นŒ์ง€ ๊ณ„์†ํ•ด์„œ ๋Œ๋ ค์•ผํ•˜๋Š”๋ฐ, ์ž์‹๋…ธ๋“œ๋ฅผ ๊ธฐ์ค€์œผ๋กœ ๋ถ€๋ชจ๋…ธ๋“œ๋ฅผ ๋น„๊ตํ•˜๋„๋ก ํ–ˆ๋‹ค.

 

์ฝ”๋“œ

T = int(input())

def change(node):
    parent = tree[node][0]
    if parent:
        if tree[parent][3] > tree[node][3]:
            tree[parent][3], tree[node][3] = tree[node][3], tree[parent][3]
    else:
        return
    change(parent)


def sum_root(N):
    global ans
    if tree[N][0] == 0:
        return
    ans += tree[tree[N][0]][3]
    sum_root(tree[N][0])


for tc in range(1, T+1):
    N = int(input())
    tmp = list(map(int, input().split()))
    tree = [[0]*4 for _ in range(N+1)]  # [๋ถ€๋ชจ๋…ธ๋“œ,์™ผ์ชฝ์ž์‹,์˜ค๋ฅธ์ชฝ์ž์‹,๋…ธ๋“œ๊ฐ’]

    for i in range(1, N+1):
        tree[i][3] = tmp[i-1]
        tree[i][0] = i // 2
        if 2 * i <= N:
            tree[i][1] = 2 * i
            tree[i][2] = 2 * i + 1
            if 2*i+1 > N:
                tree[i][2] = 0

    for i in range(1, N+1):
        change(i)

    ans = 0
    sum_root(N)

    print("#{} {}".format(tc, ans))
๋Œ“๊ธ€