-
[๋ฐฑ์ค] ์ต๋จ๊ฒฝ๋ก(๊ณจ๋4)๐ปProgramming/Algorithm 2025. 10. 1. 19:12
๋ฌธ์ ๋งํฌ
https://www.acmicpc.net/problem/1753
ํํ
ํํ๋ ์ฐ์ ์์ ํ๋ผ๊ณ ๋ ํ๋๋ฐ, ์ ์ผ ์์ ์๋ฅผ ์ ์ผ ๋จผ์ pop ํ ์ ์๋๋ก ํด์ฃผ๋ ํ์ด๋ค.
๊ทธ๋์ ํญ์ pop์ ํ๋ฉด ์ ์ผ ์์ ์๊ฐ ๋จผ์ pop์ด ๋๊ธฐ ๋๋ฌธ์ greedy ํ์์ ์ด๋ผ๊ณ ๋ถ๋ฆฌ๊ธฐ๋ ํ๋ค.
๋ค์ต์คํธ๋ผ ์๊ณ ๋ฆฌ์ฆ ์ด์ฉ ๋ฌธ์
์ฐ์ ์ด ๋ฌธ์ ์์ ์ฌ์ฉํ๋ ๊ทธ๋ํ๋ ๋จ๋ฐฉํฅ ๊ทธ๋ํ์ด๊ธฐ ๋๋ฌธ์
V, E = map(int, input().split()) K = int(input()) graph = [[] for _ in range(V + 1)] for _ in range(E): u, v, w = map(int, input().split()) graph[u].append((v, w))
๊ทธ๋ํ๋ ์ด๋ฐ์์ผ๋ก ์ฝ๋๋ฅผ ๊ตฌํํ์๋ค.
weights = [float('inf')] * (V + 1) weights[K] = 0 wq = [(0, K)]
๋ค์์ ์์์ ์ธ K๋ฅผ ๊ธฐ์ค์ผ๋ก ๊ฐ ๋ ธ๋๊น์ง์ ์ต๋จ ๊ฑฐ๋ฆฌ๋ฅผ ๋ด์ weights ๋ฐฐ์ด์ ์์ฑํ์๋ค.
ํํ๋ฅผ ๋๋ฉด์
์ด๋ฏธ ๋ ์ข์ ๊ฒฝ๋ก๋ฅผ ์ฐพ์์ ๊ฒฝ์ฐ
if weights[cnt_node] < cnt_weight: continue
๋ฅผ ํตํด ํจ์จ์ ์ผ๋ก ์ฝ๋๋ฅผ ๊ตฌํํ ์ ์๋ค.
for neighbor, weight in graph[cnt_node]: weight = cnt_weight + weight if weight < weights[neighbor]: weights[neighbor] = weight heapq.heappush(wq, (weight, neighbor))
for neighbor, weight in graph[cnt_node]: weight = cnt_weight + weight if weight < weights[neighbor]: weights[neighbor] = weight heapq.heappush(wq, (weight, neighbor))
์ฐ๊ฒฐ ๋ ธ๋๋ค์ ํ์ํ๋ฉฐ ๋๊น์ง ๋๋ค
for i in range(1, V + 1): if weights[i] == float('inf'): print('INF') else: print(weights[i])
๊ฒฐ๊ณผ๋ฅผ ์ถ๋ ฅํ๋ค
์ ์ฒด ์ฝ๋
import sys import heapq input = sys.stdin.readline V, E = map(int, input().split()) K = int(input()) graph = [[] for _ in range(V + 1)] for _ in range(E): u, v, w = map(int, input().split()) graph[u].append((v, w)) weights = [float('inf')] * (V + 1) weights[K] = 0 wq = [(0, K)] while wq: cnt_weight, cnt_node = heapq.heappop(wq) if weights[cnt_node] < cnt_weight: continue for neighbor, weight in graph[cnt_node]: weight = cnt_weight + weight if weight < weights[neighbor]: weights[neighbor] = weight heapq.heappush(wq, (weight, neighbor)) for i in range(1, V + 1): if weights[i] == float('inf'): print('INF') else: print(weights[i])
'๐ปProgramming > Algorithm' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[๋ฐฑ์ค] ์ด๋ถ ๊ทธ๋ํ(๊ณจ๋4) (0) 2025.09.10 [๋ฐฑ์ค] ํ ๋งํ (๊ณจ๋5) (0) 2025.09.09 [๋ฐฑ์ค] ๋ฒฝ ๋ถ์๊ณ ์ด๋ํ๊ธฐ(๊ณจ๋3) (0) 2025.09.08 [๋ฐฑ์ค] ํธ๋ฆฌ์ ์ง๋ฆ(๊ณจ๋4) (0) 2025.09.02 [ํ๋ก๊ทธ๋๋จธ์ค] N์ผ๋ก ํํ(level3) (0) 2025.08.29