코딩

[Atcoder] ABC 333 D - Erase Leaves

척척석사아님 2023. 12. 17. 02:04
728x90

from collections import deque
import sys
input =  sys.stdin.readline
N = int(input())
graph = [[] for _ in range (0,N+1)]
for i in range (0,N-1):
    a,b = map(int,input().split())
    graph[a].append(b)
    graph[b].append(a)
ans = []
visited = [False for _ in range (0,N)]
for i in range (0,len(graph[1])):  
    deq = deque()
    deq.appendleft(graph[1][i])
    visited[0] = True
    visited[graph[1][i]-1] = True
    cnt = 1
    while deq:
        x =  deq.popleft()
        visited[x-1] = True
        cnt += 1
        for y in graph[x]:
            if visited[y-1] == False:
                deq.appendleft(y)
                visited[y-1] = True
    ans.append(cnt) 
if len(graph[1]) == 1:
    print(1)
else:
    n = len(graph[1])-1
    ans.sort()
    answer = 0
    for i in range (0,n):
        answer += ans[i]
    print(answer - n + 1)