๐ฅ Gold4
https://www.acmicpc.net/problem/1753

โ ์ ๋ตํ์ด
import sys
from heapq import *
input=sys.stdin.readline
INF=float('inf')
def dijkstra(start):
dist=[INF]*len(graph)
dist[start]=0 #์์์ ๊ฑฐ๋ฆฌ๋ 0
q=[(0,start)] #(cost,๋
ธ๋๋ฒํธ)
while q:
cost,idx=heappop(q)
if dist[idx]<cost: # ๋ฌด์(์ด๋ฏธ ๋ฐฉ๋ฌธํ๊ฑฐ๋, ๊ฐฑ์ ํ ํ์๊ฐ ์์)
continue
# ์ธ์ ๋
ธ๋ ์ํ
for adj,d in graph[idx]: #๋
ธ๋๋ฒํธ,cost
if cost+d<dist[adj]: # ์์์ง์ ๊ธฐ์ค์ผ๋ก ํ์ฌ ๋ฐฉ๋ฌธ์ค์ธ (๊บผ๋ธ) ๋
ธ๋๊น์ง ๋น์ฉ+์ธ์ ๋
ธ๋ ๋น์ฉ์ด ๊ธฐ๋ก์ค์ธ dist๋ณด๋ค ์์ผ๋ฉด
# ๊ฐฑ์
dist[adj]=cost+d
# ๋ ์งง์ ๊ฒฝ๋ก ์ฐฝ๋ก๋ฅผ ์ฐพ์ ๋
ธ๋๋ค์ ๋ค์ ์ฐ์ ์์ ํ์ ๋ฃ๋๋ค!
heappush(q,(dist[adj],adj)) #(์๋ก์ด ์ต๋จcost,๋
ธ๋๋ฒํธ)
return dist
v,e=map(int,input().rstrip().split())
start=int(input())
graph=[[] for _ in range(v+1)]
for _ in range(e):
a,b,c=map(int,input().rstrip().split())
graph[a].append((b,c)) # (๋
ธ๋๋ฒํธ, cost) 2,5์ค 2๋ฒ ๋
ธ๋ ๋จผ์ ์ํ
# ๋ค์ต์คํธ๋ผ
distance=dijkstra(start)
for i in range(1,v+1):
print(distance[i] if distance[i]!=INF else 'INF')
์ฐ์ ์์ ํ๋ฅผ ์ด์ฉํ ๋ค์ต์คํธ๋ผ ์ต๋จ ๊ฒฝ๋ก ์๊ณ ๋ฆฌ์ฆ
โ๏ธ์ ์ฒด ๋ ธ๋์ ๊ฐ์๊ฐ 10,000๊ฐ ์ด์์ด๋ผ๋ฉด, ๋ฆฌ์คํธ๊ฐ ์๋ ์ฐ์ ์์ ํ(ํ)์ ์ฌ์ฉํด ๋ฌธ์ ๋ฅผ ํ์ด์ผํ๋ค.
๐๐ป ๋ค์ต์คํธ๋ผ ์๊ณ ๋ฆฌ์ฆ ์๊ฐ ๋ณต์ก๋
- List : O(V^2)
- Heap: O(ElogV)
'๋ฐฑ์ค' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[๋ฐฑ์ค-Python] ์ซ์์นด๋ : 10815๋ฒ (0) | 2024.08.03 |
---|---|
[๋ฐฑ์ค-Python] ํดํน : 10282๋ฒ (1) | 2024.06.14 |
[๋ฐฑ์ค-Python] ๊ฑฐ๋ถ์ด : 8911๋ฒ (1) | 2024.06.13 |
[๋ฐฑ์ค-Python] ์๊ธฐ์์ด2 : 17086๋ฒ (0) | 2024.06.13 |
[๋ฐฑ์ค-Python] ํน : 1063๋ฒ (1) | 2024.06.12 |
๐ฅ Gold4
https://www.acmicpc.net/problem/1753

โ ์ ๋ตํ์ด
import sys
from heapq import *
input=sys.stdin.readline
INF=float('inf')
def dijkstra(start):
dist=[INF]*len(graph)
dist[start]=0 #์์์ ๊ฑฐ๋ฆฌ๋ 0
q=[(0,start)] #(cost,๋
ธ๋๋ฒํธ)
while q:
cost,idx=heappop(q)
if dist[idx]<cost: # ๋ฌด์(์ด๋ฏธ ๋ฐฉ๋ฌธํ๊ฑฐ๋, ๊ฐฑ์ ํ ํ์๊ฐ ์์)
continue
# ์ธ์ ๋
ธ๋ ์ํ
for adj,d in graph[idx]: #๋
ธ๋๋ฒํธ,cost
if cost+d<dist[adj]: # ์์์ง์ ๊ธฐ์ค์ผ๋ก ํ์ฌ ๋ฐฉ๋ฌธ์ค์ธ (๊บผ๋ธ) ๋
ธ๋๊น์ง ๋น์ฉ+์ธ์ ๋
ธ๋ ๋น์ฉ์ด ๊ธฐ๋ก์ค์ธ dist๋ณด๋ค ์์ผ๋ฉด
# ๊ฐฑ์
dist[adj]=cost+d
# ๋ ์งง์ ๊ฒฝ๋ก ์ฐฝ๋ก๋ฅผ ์ฐพ์ ๋
ธ๋๋ค์ ๋ค์ ์ฐ์ ์์ ํ์ ๋ฃ๋๋ค!
heappush(q,(dist[adj],adj)) #(์๋ก์ด ์ต๋จcost,๋
ธ๋๋ฒํธ)
return dist
v,e=map(int,input().rstrip().split())
start=int(input())
graph=[[] for _ in range(v+1)]
for _ in range(e):
a,b,c=map(int,input().rstrip().split())
graph[a].append((b,c)) # (๋
ธ๋๋ฒํธ, cost) 2,5์ค 2๋ฒ ๋
ธ๋ ๋จผ์ ์ํ
# ๋ค์ต์คํธ๋ผ
distance=dijkstra(start)
for i in range(1,v+1):
print(distance[i] if distance[i]!=INF else 'INF')
์ฐ์ ์์ ํ๋ฅผ ์ด์ฉํ ๋ค์ต์คํธ๋ผ ์ต๋จ ๊ฒฝ๋ก ์๊ณ ๋ฆฌ์ฆ
โ๏ธ์ ์ฒด ๋ ธ๋์ ๊ฐ์๊ฐ 10,000๊ฐ ์ด์์ด๋ผ๋ฉด, ๋ฆฌ์คํธ๊ฐ ์๋ ์ฐ์ ์์ ํ(ํ)์ ์ฌ์ฉํด ๋ฌธ์ ๋ฅผ ํ์ด์ผํ๋ค.
๐๐ป ๋ค์ต์คํธ๋ผ ์๊ณ ๋ฆฌ์ฆ ์๊ฐ ๋ณต์ก๋
- List : O(V^2)
- Heap: O(ElogV)
'๋ฐฑ์ค' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[๋ฐฑ์ค-Python] ์ซ์์นด๋ : 10815๋ฒ (0) | 2024.08.03 |
---|---|
[๋ฐฑ์ค-Python] ํดํน : 10282๋ฒ (1) | 2024.06.14 |
[๋ฐฑ์ค-Python] ๊ฑฐ๋ถ์ด : 8911๋ฒ (1) | 2024.06.13 |
[๋ฐฑ์ค-Python] ์๊ธฐ์์ด2 : 17086๋ฒ (0) | 2024.06.13 |
[๋ฐฑ์ค-Python] ํน : 1063๋ฒ (1) | 2024.06.12 |