
๋ฐฑ์ค 1504๋ฒ: ํน์ ํ ์ต๋จ๊ฒฝ๋ก
ALGORITHM
๋ค์ต์คํธ๋ผ ์ฌ์ฉํจ
PROBLEM
์์์ 1์์ ๋์ N๊น์ง ๊ฐ
v1, v2 ๋ ์ ์ ๋ฐ๋์ ์ง๋์ผ ํจ
์์๋ ์์ , ๊ฐ์ ์ฌ์ฌ์ฉ ๊ฐ๋ฅ
ํญ์ ์ต๋จ๊ฒฝ๋ก์ฌ์ผ ํจ
APPROACH
๋ค์ต์คํธ๋ผ ์ด 3๋ฒ ๋๋ฆผ
1 → v1 → v2 → N
1 → v2 → v1 → N
๋ ๊ฒฝ๋ก ๊ณ์ฐํด์ ๋ ์งง์ ์ชฝ ์
๋ค์ต์คํธ๋ผ๋ ์์๋
ธ๋ ํ๋์์ ๋ชจ๋ ๋
ธ๋๊น์ง ๊ฑฐ๋ฆฌ ๋ฐฐ์ด ๋ง๋ค๊ณ
ํ์ํ ๊ตฌ๊ฐ๋ง ๊บผ๋ด์ ๋ํจ
๋ชฉํ๋
ธ๋๋ ํจ์ ์์์ ์ ์
IMPLEMENTATION
๊ทธ๋ํ๋ (๊ฐ์ค์น, ๋ค์๋
ธ๋) ํํ๋ก ์ ์ฅ
heapq์ (๋์ ๊ฐ์ค์น, ๋
ธ๋)๋ก ๋ฃ๊ณ ์ต์๊ฑฐ๋ฆฌ ๊ฐฑ์
์์๋
ธ๋ ๋ฐ๋๋ฉด ํ๊ณผ ๊ฑฐ๋ฆฌ๋ฐฐ์ด ์๋ก ๋ง๋ฆ
๊ฒฝ๋ก ์์ผ๋ฉด INF ๋จ์ → -1 ์ถ๋ ฅ
SUMMARY
๊ฒฝ๋ก ์ถ๋ ฅ ์ ํจ, ๊ฐ์ค์น๋ง ํ์
๋ค์ต์คํธ๋ผ 3๋ฒ, ๋ ์ผ์ด์ค ๋น๊ต๋ก ๋๋
#dijkstra,shortest_path
import sys,heapq
input=sys.stdin.readline
def dijkstra(start,n,graph):
heap=[]
heapq.heappush(heap,(0,start)) #(๊ฐ์ค์น,์์๋
ธ๋)
INF=float('inf')
distance=[INF]*(n+1)
distance[start]=0
while heap:
current_weight,current_node=heapq.heappop(heap)
for next_weight,next_node in graph[current_node]:
accumulated_weight=current_weight+next_weight
if accumulated_weight<distance[next_node]:
distance[next_node]=accumulated_weight
heapq.heappush(heap,(accumulated_weight,next_node))
return distance
n,e=map(int,input().split())
graph=[[] for _ in range(n+1)]
for _ in range(e):
start,end,weight=map(int,input().split())
graph[start].append((weight,end))
graph[end].append((weight,start))
v1,v2=map(int,input().split())
distance_from_start=dijkstra(1,n,graph)
distance_from_v1=dijkstra(v1,n,graph)
distance_from_v2=dijkstra(v2,n,graph)
#1->v1->v2->n
shortest_path1=distance_from_start[v1]+distance_from_v1[v2]+distance_from_v2[n]
#1->v2->v1->n
shortest_path2=distance_from_start[v2]+distance_from_v2[v1]+distance_from_v1[n]
shorest_path=min(shortest_path1,shortest_path2)
print(shorest_path if shorest_path<float('inf') else -1)'๐ Algorithm > BOJ' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
| โ BOJ 2448 - ์ฌ๊ท ๋ณ์ฐ๊ธฐ (0) | 2025.07.05 |
|---|---|
| โ BOJ 1987 - DFS, Backtracking, Bitmasking (1) | 2025.07.04 |
| โ BOJ 17070 - 3์ฐจ์ DP (0) | 2025.07.03 |
| โ BOJ 15686 - ์กฐํฉ ๋ฐฑํธ๋ํน (0) | 2025.07.02 |
| โ BOJ 1043 - ์ ๋์จ ํ์ธ๋ (0) | 2025.07.02 |