Skip to content

Commit a81b14b

Browse files
committed
solved(python): baekjoon 1167
1 parent 9a6a460 commit a81b14b

File tree

4 files changed

+89
-0
lines changed

4 files changed

+89
-0
lines changed

baekjoon/python/1167/__init__.py

Whitespace-only changes.

baekjoon/python/1167/main.py

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
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.v = int(read())
10+
self.data = defaultdict(list[tuple[int, int]])
11+
12+
for line in [list(map(int, read().split())) for _ in range(self.v)]:
13+
for idx in range(1, len(line) - 1, 2):
14+
self.data[line[0]].append((line[idx], line[idx + 1]))
15+
16+
def solve(self) -> None:
17+
node, maximum = self.dfs(1)
18+
19+
print(max(maximum, self.dfs(node)[1]))
20+
21+
def dfs(self, start_node: int) -> tuple[int, int]:
22+
queue, visited, maximum, node = deque([(start_node, 0)]), {start_node}, 0, start_node
23+
24+
while queue:
25+
current, weight = queue.pop()
26+
if weight > maximum:
27+
maximum, node = weight, current
28+
29+
for next_node, next_weight in self.data[current]:
30+
if next_node not in visited:
31+
visited.add(next_node)
32+
queue.append((next_node, weight + next_weight))
33+
34+
return node, maximum
35+
36+
37+
if __name__ == "__main__":
38+
Problem().solve()

baekjoon/python/1167/sample.json

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

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