Skip to content

Commit 11e702b

Browse files
committed
백준 11725번 트리의 부모 찾기
문제 링크: https://www.acmicpc.net/problem/11725
1 parent 5e5055e commit 11e702b

File tree

6 files changed

+98
-0
lines changed

6 files changed

+98
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
import sys
2+
from typing import List, Deque
3+
from collections import deque
4+
5+
6+
def solve():
7+
N = int(sys.stdin.readline().strip())
8+
nodes: List[List[int]] = [[] for n in range(N + 1)]
9+
parents: List[int] = [0 for _ in range(N + 1)]
10+
parents[1] = 1
11+
12+
for _ in range(N - 1):
13+
fr, to = list(map(int, sys.stdin.readline().strip().split(' ')))
14+
nodes[fr].append(to)
15+
nodes[to].append(fr)
16+
17+
bfs(1, nodes, parents)
18+
19+
for idx in range(2, N + 1):
20+
print(parents[idx])
21+
22+
23+
def bfs(p, nodes, parents):
24+
queue: Deque = deque([p])
25+
26+
while queue:
27+
p = queue.popleft()
28+
29+
for child in nodes[p]:
30+
if parents[child] == 0:
31+
parents[child] = p
32+
queue.append(child)
33+
34+
35+
if __name__ == '__main__':
36+
solve()
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
7
2+
1 6
3+
6 3
4+
3 5
5+
4 1
6+
2 4
7+
4 7
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
4
2+
6
3+
1
4+
3
5+
1
6+
4
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
12
2+
1 2
3+
1 3
4+
2 4
5+
3 5
6+
3 6
7+
4 7
8+
4 8
9+
5 9
10+
5 10
11+
6 11
12+
6 12
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
1
2+
1
3+
2
4+
3
5+
3
6+
4
7+
4
8+
5
9+
5
10+
6
11+
6
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
import sys
2+
from pathlib import Path
3+
from unittest import TestCase
4+
from main import solve
5+
6+
7+
class Test(TestCase):
8+
def my_solve(self, testcase_input):
9+
sys.stdin = open(testcase_input, 'r')
10+
stdout = sys.stdout
11+
sys.stdout = open('stdout.txt', 'w')
12+
solve()
13+
sys.stdout.close()
14+
sys.stdout = stdout
15+
16+
def test_solve(self, testcase_number: str):
17+
self.my_solve('test' + testcase_number + '.txt')
18+
self.assertEqual(
19+
Path('test' + testcase_number + '_answer.txt').read_text().strip(),
20+
Path('stdout.txt').read_text().strip())
21+
22+
def test1_solve(self):
23+
self.test_solve('1')
24+
25+
def test2_solve(self):
26+
self.test_solve('2')

0 commit comments

Comments
 (0)