토니의 연습장

트리 예제 본문

Algorithm/Ch 3. 응용 자료구조

트리 예제

bellmake 2025. 1. 4. 11:27

https://www.acmicpc.net/problem/1068

N = int(input())
parent = list(map(int, input().split()))
R = int(input())

# 루트 노드 찾기
for i in range(N):
    if parent[i]==-1:
        root = i
        break
    
# 사라지는 노드 판별
black = [0]*N
for i in range(N):
    u = i
    while True:
        if u == R:
            black[i] = 1
            break
        if u == root:
            break
        
        u = parent[u]
        
# 자식 있는 노드 색칠
red = [0]*N
for i in range(N):
    if black[i] == 1: # 제거된 노드
        continue
    
    if i == root: # 부모 없음
        continue
    
    # 부모 있음 -> 부모 노드로 가서 자식이 있음 체크
    red[parent[i]] = 1
    
count = 0

for i in range(N):
    if black[i] == 1 or red[i] == 1:
        continue
    
    count += 1
    
print(count)

 

https://www.acmicpc.net/problem/14267

N, M = list(map(int, input().split()))

parent = list(map(int, input().split()))

for i in range(1,N):
    parent[i] -= 1

good = [0]*N    
for _ in range(M):
    id, score = list(map(int, input().split()))
    good[id-1] += score
    
total_good = [0]*M

total_good = [0]*N
for i in range(1,N):
    total_good[i] = total_good[parent[i]]+good[i]
    
print(*total_good)

'Algorithm > Ch 3. 응용 자료구조' 카테고리의 다른 글

해쉬 예제  (1) 2025.01.04
우선 순위 큐 예제  (0) 2025.01.04
그래프 예제  (1) 2025.01.04
누적합 배열 예제  (2) 2024.09.18