Skip to content

Commit f41f072

Browse files
committed
solved(python): baekjoon 2098
1 parent 81d2f1f commit f41f072

File tree

4 files changed

+101
-0
lines changed

4 files changed

+101
-0
lines changed

baekjoon/python/2098/__init__.py

Whitespace-only changes.

baekjoon/python/2098/main.py

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
import math
2+
import sys
3+
4+
read = lambda: sys.stdin.readline().rstrip()
5+
6+
7+
class Problem:
8+
def __init__(self):
9+
self.n = int(read())
10+
self.data = [list(map(int, read().split())) for _ in range(self.n)]
11+
12+
def solve(self) -> None:
13+
dp = [[math.inf for _ in range(1 << self.n)] for _ in range(self.n)]
14+
dp[0][1 << 0] = 0
15+
16+
for visited in range(1 << self.n):
17+
for node in range(self.n):
18+
if not (1 << node & visited):
19+
continue
20+
21+
for next_node, next_weight in enumerate(self.data[node]):
22+
if (1 << next_node) & visited or next_weight == 0:
23+
continue
24+
25+
dp[next_node][visited | 1 << next_node] = min(
26+
dp[next_node][visited | 1 << next_node],
27+
next_weight + dp[node][visited],
28+
)
29+
30+
minimum = math.inf
31+
for node in range(1, self.n):
32+
if self.data[node][0] != 0:
33+
minimum = min(minimum, dp[node][(1 << self.n) - 1] + self.data[node][0])
34+
35+
print(minimum)
36+
37+
38+
if __name__ == "__main__":
39+
Problem().solve()

baekjoon/python/2098/sample.json

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

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