728x90
๋ฌธ์
ํ์ด
1. ์ฃผ์ด์ง ์ ๋ ฅ์ ์๋ฐฉํฅ ๊ฐ์ ์ด๋ฏ๋ก ๋จ๋ฐฉํฅ ๊ฐ์ ์ผ๋ก ๋ง๋ค์ด์ค์ผํจ
2. ํฌ์๋ฐฐ์ด ์ฌ์ฉ
https://hello-capo.netlify.app/algorithm-sparse-table/
3. LCA์ ์ ์ฌํ๊ฒ ๋ ธ๋ ํ์
https://cyberflower.github.io/2019/07/22/LCA.html
์ฝ๋
import sys, math
input = sys.stdin.readline
#์๋ฐฉํฅ ๊ทธ๋ํ๋ฅผ ๋จ๋ฐฉํฅ์ผ๋ก ๋ฐ๊ฟ
def dfs(x):
visited[x] = True
for next, power in tmp[x]:
if not visited[next]:
arr[next] = [x, power]
dfs(next)
#ํฌ์ ํ๋ ฌ ์ด์ฉ
def lca(j, w):
for i in range(int(math.log2(n)), -1, -1):
if spareTable[i][j][1] <= w and spareTable[i][j][0] != 0:
w -= spareTable[i][j][1]
j = spareTable[i][j][0]
return j
n = int(input().rstrip())
ant = [0] + [int(input().rstrip()) for _ in range(n)] #๊ฐ๋ฏธ ์๋์ง
arr = [[] for _ in range(n + 1)] #๋จ๋ฐฉํฅ ๊ทธ๋ํ
tmp = [[] for _ in range(n + 1)] #์๋ฐฉํฅ ๊ทธ๋ํ(์์)
visited = [False] * (n + 1) #๋ฐฉ๋ฌธ ์ฌ๋ถ
#์๋ฐฉํฅ ๊ทธ๋ํ ์
๋ ฅ
for _ in range(n - 1):
a, b, c = map(int, input().rstrip().split())
tmp[b].append([a, c])
tmp[a].append([b, c])
#๋จ๋ฐฉํฅ ๊ทธ๋ํ๋ก ๋ง๋ค์ด์ค
dfs(1)
arr[1] = [1, 0]
#ํฌ์ ํ๋ ฌ ์์ฑ
spareTable = [[[0, 0] for _ in range(n + 1)] for _ in range(int(math.log2(n)) + 1)]
for i in range(1, n + 1):
spareTable[0][i] = arr[i]
for k in range(1, int(math.log2(n)) + 1):
for i in range(1, n + 1):
next, power = spareTable[k - 1][i]
spareTable[k][i] = [spareTable[k - 1][next][0], power + spareTable[k - 1][next][1]]
for i in range(1, n + 1):
print(lca(i, ant[i]))
๋ง๋ฌด๋ฆฌ
๊ฐ์ธ์ ์ผ๋ก ๋๋ฌด ์ด๋ ค์ ๋ค... ๊ตฌ๊ธ๋งํด์ ๊ฒจ์ฐ ํ
728x90