From 6855b045dc6f1a14d2fe600c4e02c5f2cc13f6f4 Mon Sep 17 00:00:00 2001 From: tgyuuAn Date: Sun, 25 Aug 2024 14:48:54 +0900 Subject: [PATCH] 2024-08-23 --- ...0 \353\247\210\353\213\210\354\225\204.py" | 31 +++++++++++++++++++ tgyuuAn/README.md | 1 + 2 files changed, 32 insertions(+) create mode 100644 "tgyuuAn/DFS/\353\223\261\354\202\260 \353\247\210\353\213\210\354\225\204.py" diff --git "a/tgyuuAn/DFS/\353\223\261\354\202\260 \353\247\210\353\213\210\354\225\204.py" "b/tgyuuAn/DFS/\353\223\261\354\202\260 \353\247\210\353\213\210\354\225\204.py" new file mode 100644 index 00000000..7af2aa8f --- /dev/null +++ "b/tgyuuAn/DFS/\353\223\261\354\202\260 \353\247\210\353\213\210\354\225\204.py" @@ -0,0 +1,31 @@ +import sys +sys.setrecursionlimit(10 ** 6) + +def input(): return sys.stdin.readline().rstrip() + +N = int(input()) +# N = 30 만 -> O(N*log(N)) + +tree = [[] for _ in range(N+1)] +for _ in range(N-1): + node1, node2 = map(int, input().split()) + tree[node1].append(node2) + tree[node2].append(node1) + +answer = 0 +def dfs(now_idx, visited, tree): + global answer + + temp_cnt = 1 + for next_node in tree[now_idx]: + if next_node in visited: continue + visited.add(next_node) + temp = dfs(next_node, visited, tree) + answer += temp * (temp-1) // 2 + answer += temp * (N-temp) + temp_cnt += temp + + return temp_cnt + +dfs(1,{1,}, tree) +print(answer) diff --git a/tgyuuAn/README.md b/tgyuuAn/README.md index 73034d56..dfd14f36 100644 --- a/tgyuuAn/README.md +++ b/tgyuuAn/README.md @@ -77,4 +77,5 @@ | 68차시 | 2024.08.06 | 그리디 | 가희와 탑 | https://github.com/AlgoLeadMe/AlgoLeadMe-1/pull/226 | 69차시 | 2024.08.10 | 누적합, 수학 | 1의 개수 세기 | https://github.com/AlgoLeadMe/AlgoLeadMe-1/pull/228 | 70차시 | 2024.08.16 | 스택 | 탑 보기 | https://github.com/AlgoLeadMe/AlgoLeadMe-1/pull/232 +| 72차시 | 2024.08.23 | DFS + 트리 | 등산 마니아 | https://github.com/AlgoLeadMe/AlgoLeadMe-1/pull/238 ---