๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

๐Ÿ’ปAlgorithm/PS

[BOJ/๋ฐฑ์ค€] 17396 ๋ฐฑ๋„์–ด - ํŒŒ์ด์ฌ

๋ฌธ์ œ

๋ฐฑ์ค€ 17396 ๋ฐฑ๋„์–ด

 

https://www.acmicpc.net/problem/17396

 

17396๋ฒˆ: ๋ฐฑ๋„์–ด

์ฒซ ๋ฒˆ์งธ ์ค„์— ๋ถ„๊ธฐ์ ์˜ ์ˆ˜์™€ ๋ถ„๊ธฐ์ ๋“ค์„ ์ž‡๋Š” ๊ธธ์˜ ์ˆ˜๋ฅผ ์˜๋ฏธํ•˜๋Š” ๋‘ ์ž์—ฐ์ˆ˜ N๊ณผ M์ด ๊ณต๋ฐฑ์œผ๋กœ ๊ตฌ๋ถ„๋˜์–ด ์ฃผ์–ด์ง„๋‹ค.(1 ≤ N ≤ 100,000, 1 ≤ M ≤ 300,000) ๋‘ ๋ฒˆ์งธ ์ค„์— ๊ฐ ๋ถ„๊ธฐ์ ์ด ์ ์˜ ์‹œ์•ผ์— ๋ณด์ด๋Š”

www.acmicpc.net

 

๋ฌธ์ œํ’€์ด

๋ฐฑ๋„์–ด ํ•˜๋Š”๋ฐ ๊ฑธ๋ฆฌ๋Š” ์ตœ๋‹จ์‹œ๊ฐ„์„ ๊ตฌํ•˜๋Š” ๋ฌธ์ œ๋กœ ๊ฐ๊ฐ์˜ ๋ถ„๊ธฐ์ ์œผ๋กœ ๊ฐ€๋Š” ์‹œ๊ฐ„์ด ๊ฐ€์ค‘์น˜๊ฐ€ ๋˜๋Š” ๋‹ค์ต์ŠคํŠธ๋ผ ๋ฌธ์ œ

(n-1)๋ฒˆ์งธ ๋ถ„๊ธฐ์ ์€ ๊ฐ’์ด 1์ด์–ด๋„ ๊ฐˆ ์ˆ˜ ์žˆ๋Š” ๋ถ„๊ธฐ์ ์ด๊ธฐ์— ๊ฐ’์ด 0์ธ ๋ถ„๊ธฐ์ ๊ณผ ๋™์ผ

์ด๋ฅผ ์ œ์™ธํ•œ ๋ถ„๊ธฐ์ ์€ ๊ฐ’์ด 1์ด๋ผ๋ฉด continue ํ•ด์ฃผ๊ธฐ

 

๊ฐœ๋…์ •๋ฆฌ

๋‹ค์ต์ŠคํŠธ๋ผ๋Š” ์ตœ๋‹จ๊ฒฝ๋กœ ํƒ์ƒ‰ ์•Œ๊ณ ๋ฆฌ์ฆ˜์œผ๋กœ ์‹œ์ž‘์ ์œผ๋กœ๋ถ€ํ„ฐ ๋‹ค๋ฅธ ๋ชจ๋“  ์ ๊นŒ์ง€์˜ ์ตœ๋‹จ๊ฑฐ๋ฆฌ๋ฅผ ๊ตฌํ•˜๋Š”๋ฐ ์“ฐ์ธ๋‹ค.

bfs๋„ ์ตœ๋‹จ๊ฒฝ๋กœ ํƒ์ƒ‰ ์•Œ๊ณ ๋ฆฌ์ฆ˜์ด์ง€๋งŒ ์ฐจ์ด์ ์ด ์žˆ๋‹ค๋ฉด, bfs๋Š” ๊ฐ„์„ ์˜ ๊ฐ€์ค‘์น˜๊ฐ€ 1๋กœ ๋™์ผํ•œ ๊ฒฝ์šฐ์— ์ ์šฉํ•˜๊ณ 

๋‹ค์ต์ŠคํŠธ๋ผ๋Š” ๊ฐ€์ค‘์น˜๊ฐ€ ์Œ์ด ์•„๋‹Œ ๊ฐ’์ธ ๊ฒฝ์šฐ์— ์ ์šฉํ•œ๋‹ค.

heapq ๋ชจ๋“ˆ์„ ์‚ฌ์šฉํ•˜์—ฌ ๊ตฌํ˜„!

 

์ฝ”๋“œ

import sys
import heapq
inf=sys.maxsize
input=sys.stdin.readline

n,m=map(int,input().split())
can=list(map(int,input().split()))
can[-1]=0 ##๋„ฅ์„œ์Šค์—๋Š” ๋ฐฉ๋ฌธ ๊ฐ€๋Šฅ
link=[[] for _ in range(n)]
for i in range(m):
     a,b,t=map(int,input().split())
     link[a].append([b,t])
     link[b].append([a,t])

heap=[]
heapq.heappush(heap,[0,0])
dp=[inf for _ in range(n)]
dp[0]=0

while(heap):
    w,now=heapq.heappop(heap)
    if dp[now]<w:
        continue
    else:
        for nxt,nxt_w in link[now]:
            wei=nxt_w+w
            if dp[nxt]>wei and can[nxt]==0:
                dp[nxt]=wei
                heapq.heappush(heap,[wei,nxt])

result=dp[n-1]
print(result if result<inf else -1)

 

 

์–ด๋ ค์› ๋˜ ์ 

์ฒ˜์Œ์— dp[now]<w์ธ ๊ฒฝ์šฐ ์ฆ‰, ๊ฐฑ์‹  ์ „ ๊ฐ’์ด ์ด๋ฏธ ๋” ์ž‘์€ ๊ฒฝ์šฐ๋ฅผ continueํ•˜์ง€ ์•Š๊ณ  ํ’€์—ˆ๋”๋‹ˆ ์‹œ๊ฐ„์ดˆ๊ณผ๊ฐ€ ๋‚ฌ๋‹ค.

๋‹ค์ต์ŠคํŠธ๋ผ ์•Œ๊ณ ๋ฆฌ์ฆ˜์„ ์‚ฌ์šฉํ• ๋•Œ๋Š” continue๋ฌธ์„ ์ ์ ˆํžˆ ํ™œ์šฉํ•ด์„œ ์‹œ๊ฐ„์„ ์ค„์ด๋Š” ๊ฒƒ์ด ์ค‘์š”ํ•œ ๋“ฏ!!