Skip to content

Commit

Permalink
Merge pull request #96 from AlgoLeadMe/26-seongwon030
Browse files Browse the repository at this point in the history
26-seongwon030
  • Loading branch information
seongwon030 authored Sep 2, 2024
2 parents 23ba0a7 + aee3b08 commit f0978ec
Showing 1 changed file with 51 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import heapq
import sys

input = sys.stdin.readline

n,e = map(int,input().split())
graph = [[] for _ in range(n+1)]

# ์ž…๋ ฅ
for _ in range(e):
a,b,c = map(int,input().split())

graph[a].append([b,c])
graph[b].append([a,c])

v1 ,v2 = map(int,input().split())

# ๋ฐ์ดํฌ ์ŠคํŠธ๋ผ ์•Œ๊ณ ๋ฆฌ์ฆ˜
def di(start,size):
# ์‚ฌ์šฉํ•œ ๊ธธ ๊ณ„์† ์‚ฌ์šฉ ๊ฐ€๋Šฅ ํ•˜๋ฏ€๋กœ ๊ณ„์† ์ดˆ๊ธฐํ™” ํ•œ๋‹ค.
distance = [float('inf')] * (size+1)
q = []
heapq.heappush(q, [0,start])
distance[start] = 0

while q:
dist, node = heapq.heappop(q)

if distance[node] < dist:
continue
for n,w in graph[node]:
cost = dist + w

if distance[n] > cost:
distance[n]= cost
heapq.heappush(q,[cost,n])

return distance

#๊ฐ๊ฐ 1,v1,v2๊ฐ€ ์‹œ์ž‘์ ์œผ๋กœ ๊ฐ ๋…ธ๋“œ์— ๋Œ€ํ•œ ์ตœ๋‹จ ๊ฒฝ๋กœ๋ฅผ ๋‹ด๊ณ  ์žˆ๋‹ค.
d1 = di(1,n)
d2 = di(v1,n)
d3 = di(v2,n)
# v1์„ ๋จผ์ € ๋“ค๋ฆฌ๊ฑฐ๋‚˜ v2๋ฅผ ๋จผ์ € ๋“ค๋ฆฌ๊ฑฐ๋‚˜ ๋น„๊ตํ•ด์„œ ๋” ์งง์€ ๊ฑฐ๋ฆฌ๋ฅผ ์‚ฌ์šฉํ•œ๋‹ค.
result = min(d1[v2]+d2[n]+d3[v1],d1[v1]+d2[v2]+d3[n])


if result == float('inf'):
print(-1)
else:
print(result)

0 comments on commit f0978ec

Please sign in to comment.