Skip to content

Commit 1c47cf0

Browse files
committed
solved(python): baekjoon 2623
1 parent 43555a1 commit 1c47cf0

4 files changed

Lines changed: 98 additions & 0 deletions

File tree

baekjoon/python/2623/__init__.py

Whitespace-only changes.

baekjoon/python/2623/main.py

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
import sys
2+
from collections import defaultdict, deque
3+
4+
read = lambda: sys.stdin.readline().rstrip()
5+
6+
7+
class Problem:
8+
def __init__(self):
9+
self.n, self.m = map(int, read().split())
10+
self.data = defaultdict(list)
11+
self.weights = [0 for _ in range(self.n + 1)]
12+
13+
for _ in range(self.m):
14+
values = list(map(int, read().split()))
15+
for idx in range(2, values[0] + 1):
16+
self.data[values[idx]].append(values[idx - 1])
17+
self.weights[values[idx - 1]] += 1
18+
19+
def solve(self) -> None:
20+
print(*self.topology_sort(), sep="\n")
21+
22+
def topology_sort(self) -> list[int]:
23+
queue, sequence = (
24+
deque(filter(lambda x: self.weights[x] == 0, range(1, self.n + 1))),
25+
[],
26+
)
27+
28+
while queue:
29+
num = queue.popleft()
30+
if num in sequence:
31+
continue
32+
33+
sequence.append(num)
34+
35+
for next_num in self.data[num][-1::-1]:
36+
self.weights[next_num] -= 1
37+
if self.weights[next_num] == 0:
38+
queue.append(next_num)
39+
40+
return sequence[-1::-1] if len(sequence) == self.n else [0]
41+
42+
43+
if __name__ == "__main__":
44+
Problem().solve()

baekjoon/python/2623/sample.json

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
[
2+
{
3+
"input": [
4+
"6 3",
5+
"3 1 4 3",
6+
"4 6 2 5 4",
7+
"2 2 3"
8+
],
9+
"expected": [
10+
"6",
11+
"2",
12+
"1",
13+
"5",
14+
"4",
15+
"3"
16+
]
17+
}
18+
]

baekjoon/python/2623/test_main.py

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
import json
2+
import os.path
3+
import unittest
4+
from io import StringIO
5+
from unittest.mock import patch
6+
7+
from parameterized import parameterized
8+
9+
from main import Problem
10+
11+
12+
def load_sample(filename: str):
13+
path = os.path.join(os.path.dirname(os.path.abspath(__file__)), filename)
14+
15+
with open(path, "r") as file:
16+
return [(case["input"], case["expected"]) for case in json.load(file)]
17+
18+
19+
class TestCase(unittest.TestCase):
20+
@parameterized.expand(load_sample("sample.json"))
21+
def test_case(self, case: str, expected: list[str]):
22+
# When
23+
with (
24+
patch("sys.stdin.readline", side_effect=case),
25+
patch("sys.stdout", new_callable=StringIO) as output,
26+
):
27+
Problem().solve()
28+
29+
result = output.getvalue().rstrip()
30+
31+
# Then
32+
self.assertEqual("\n".join(expected), result)
33+
34+
35+
if __name__ == "__main__":
36+
unittest.main()

0 commit comments

Comments
 (0)