Skip to content

Commit 36e449f

Browse files
committed
solved(python): baekjoon 1766
1 parent 7290853 commit 36e449f

4 files changed

Lines changed: 93 additions & 0 deletions

File tree

baekjoon/python/1766/__init__.py

Whitespace-only changes.

baekjoon/python/1766/main.py

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

baekjoon/python/1766/sample.json

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

baekjoon/python/1766/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)