Skip to content

Commit 5e5e31e

Browse files
committed
solved(python): baekjoon 1647
1 parent a8dcea2 commit 5e5e31e

4 files changed

Lines changed: 98 additions & 0 deletions

File tree

baekjoon/python/1647/__init__.py

Whitespace-only changes.

baekjoon/python/1647/main.py

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
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 = defaultdict(list)
12+
13+
for _ in range(self.m):
14+
src, dest, cost = map(int, read().split())
15+
self.data[src].append((cost, dest))
16+
self.data[dest].append((cost, src))
17+
18+
def solve(self) -> None:
19+
print(self.mst(1))
20+
21+
def mst(self, start_node: int) -> int:
22+
queue, visited, costs, max_cost = ([(0, start_node)], set(), 0, 0)
23+
24+
while queue:
25+
cost, node = heapq.heappop(queue)
26+
if node in visited:
27+
continue
28+
29+
visited.add(node)
30+
costs, max_cost = costs + cost, max(max_cost, cost)
31+
32+
for new_cost, dest in self.data[node]:
33+
if dest not in visited:
34+
heapq.heappush(queue, (new_cost, dest))
35+
36+
return costs - max_cost
37+
38+
39+
if __name__ == "__main__":
40+
Problem().solve()

baekjoon/python/1647/sample.json

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

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