Skip to content

Commit 8653390

Browse files
author
jiyoung1814
committed
[BOJ] 최소비용 구하기 / 골드5 / 30분
1 parent ee67f12 commit 8653390

File tree

1 file changed

+116
-0
lines changed

1 file changed

+116
-0
lines changed

jiyoung1814/boj_graph_min_cost.py

Lines changed: 116 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,116 @@
1+
# import sys
2+
# sys.setrecursionlimit(10**6)
3+
#
4+
# def find_parent(parent, x):
5+
# if parent[x] != x:
6+
# parent[x] = find_parent(parent, parent[x])
7+
# return parent[x]
8+
#
9+
# def union(parent, a, b):
10+
# a = find_parent(parent, a)
11+
# b = find_parent(parent, b)
12+
#
13+
# if a < b:
14+
# parent[b] = a
15+
# else:
16+
# parent[a] = b
17+
#
18+
#
19+
# city_num = int(sys.stdin.readline())
20+
# bus_num = int(sys.stdin.readline())
21+
#
22+
#
23+
# edges = []
24+
# parent = [i for i in range(city_num+1)]
25+
#
26+
# for bus in range(bus_num):
27+
# a, b, cost = map(int, sys.stdin.readline().split())
28+
# edges.append((cost, a, b))
29+
#
30+
# edges.sort()
31+
#
32+
#
33+
# for edge in edges:
34+
# cost, a, b = edge
35+
# if find_parent(parent, a) != find_parent(parent, b):
36+
# union(parent, a, b)
37+
#
38+
#
39+
# start, end = map(int, sys.stdin.readline().split())
40+
#
41+
#
42+
# min_cost = 0
43+
# now_city = start
44+
#
45+
# while True:
46+
# edge = next((edge for edge in edges if edge[1] == now_city), None)
47+
#
48+
# if edge is None:
49+
# break
50+
#
51+
# cost, a, b = edge
52+
#
53+
# min_cost += cost
54+
# now_city = b
55+
#
56+
# if now_city == end:
57+
# break
58+
#
59+
# print(min_cost)
60+
61+
import sys
62+
import heapq
63+
64+
INF = float('inf')
65+
66+
def dijkstra(start, end, n, adj_list):
67+
dist = [INF] * (n+1)
68+
dist[start] = 0
69+
70+
pq = []
71+
heapq.heappush(pq, (0, start)) # (비용, 도시)
72+
73+
while pq:
74+
now_cost, now_node = heapq.heappop(pq)
75+
76+
if now_cost > dist[now_node]: # 현재 비용이 큐에 있는 비용보다 작을 때만 갱신
77+
continue
78+
79+
for new_node, new_cost in adj_list[now_node]:
80+
new_cost = now_cost + new_cost
81+
82+
if new_cost < dist[new_node]:
83+
dist[new_node] = new_cost
84+
heapq.heappush(pq, (new_cost, new_node))
85+
86+
return dist[end]
87+
88+
89+
city_num = int(sys.stdin.readline())
90+
bus_num = int(sys.stdin.readline())
91+
92+
adj_list = {i: [] for i in range(1, city_num + 1)}
93+
94+
for _ in range(bus_num):
95+
a, b, cost = map(int, sys.stdin.readline().split())
96+
adj_list[a].append((b, cost))
97+
98+
start, end = map(int, sys.stdin.readline().split())
99+
# city_num = 5
100+
# bus_num = 8
101+
# adj_list = {i: [] for i in range(1, city_num+1)}
102+
# edges = [
103+
# (1, 2, 2),
104+
# (1, 3, 3),
105+
# (1, 4, 1),
106+
# (1, 5, 10),
107+
# (2, 4, 2),
108+
# (3, 4, 1),
109+
# (3, 5, 1),
110+
# (4, 5, 3),
111+
# ]
112+
# start = 1
113+
# end = 5
114+
115+
result = dijkstra(start, end, city_num, adj_list)
116+
print(result)

0 commit comments

Comments
 (0)