๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿƒ algorithm/boj

BOJ 11952 - ์ข€๋น„

by HandHand 2021. 3. 8.

๋ฌธ์ œ

๋ฐฑ์ค€ ์˜จ๋ผ์ธ ์ €์ง€ - 11952๋ฒˆ

ํ’€์ด ๊ณผ์ •

๋ฌธ์ œ์—์„œ ์ฃผ์–ด์ง„ ์ข€๋น„๋กœ ์ ๋ น๋œ ๋„์‹œ๋“ค์„ ์ด์šฉํ•ด์„œ ์œ„ํ—˜ํ•œ ์ง€์—ญ์„ ์ฐพ๊ณ ,

์ด๋ฅผ ํ†ตํ•ด ๋„์‹œ ๋ฐฉ๋ฌธ ๋น„์šฉ์„ ๊ณ„์‚ฐํ•˜๊ณ  ๋‹ค์ต์ŠคํŠธ๋ผ ์•Œ๊ณ ๋ฆฌ์ฆ˜์„ ์ด์šฉํ•ด ์ตœ๋‹จ๊ฑฐ๋ฆฌ๋ฅผ ๊ณ„์‚ฐํ•ฉ๋‹ˆ๋‹ค.

์ด๋•Œ ๋„์‹œ์—๊ฒŒ ์ ๋ น๋‹นํ•œ ๋„์‹œ๋Š” ์ตœ๋‹จ ๊ฑฐ๋ฆฌ ๊ณ„์‚ฐ ์‹œ ๊ณ ๋ คํ•˜์ง€ ์•Š๋„๋ก ํ•˜๋Š” ๊ฒƒ์— ์œ ์˜ํ•ฉ๋‹ˆ๋‹ค.

์ข€๋น„์—๊ฒŒ ์ ๋ น๋‹นํ•œ ๋„์‹œ๋ฅผ ๊ธฐ์ค€์œผ๋กœ S ์ดํ•˜์˜ ๊ฑฐ๋ฆฌ๋ฅผ ๊ฐ€์ง€๋Š” ์œ„ํ—˜ํ•œ ๋„์‹œ๋ฅผ ํŒ๋‹จํ•˜๊ธฐ ์œ„ํ•ด์„œ๋Š” BFS ๋ฅผ ์ด์šฉํ–ˆ์Šต๋‹ˆ๋‹ค.

์ฝ”๋“œ


import sys
from collections import deque
import heapq

N, M, K, S = list(map(int, sys.stdin.readline().split()))
P, Q = list(map(int, sys.stdin.readline().split()))
occupied = [int(sys.stdin.readline().strip()) for _ in range(K)]
edges = [list(map(int, sys.stdin.readline().split())) for _ in range(M)]


def make_graph():
    graph = [[] for _ in range(N + 1)]

    for frm, to in edges:
        graph[frm].append(to)
        graph[to].append(frm)

    return graph


def find_zombie_land(graph):
    zombie_land = [0] * (N + 1)

    for start in occupied:
        lands = bfs(start, graph, S)
        for land in lands:
            zombie_land[land] = 1

    zombie_land[1] = 0
    zombie_land[N] = 0

    return zombie_land


def bfs(start, graph, offset):
    visit = [0] * (N + 1)
    q = deque()

    ret = []
    visit[start] = 1
    q.append([start, 0])

    while q:
        here, move = q.popleft()

        if move > offset:
            continue
        else:
            ret.append(here)

        for there in graph[here]:
            if not visit[there]:
                visit[there] = 1
                q.append([there, move + 1])

    return ret


def dijkstra(graph, zombie_land):
    pq = []
    dist = [sys.maxsize] * (N + 1)

    dist[1] = 0
    heapq.heappush(pq, [0, 1])

    while pq:
        cost, here = heapq.heappop(pq)

        if dist[here] < cost:
            continue

        for there in graph[here]:
            if there in occupied:
                continue

            next_cost = cost + (Q if zombie_land[there] else P)
            if next_cost < dist[there]:
                dist[there] = next_cost
                heapq.heappush(pq, [next_cost, there])

    return dist[N] - P


def solution():
    graph = make_graph()
    zombie_land = find_zombie_land(graph)
    answer = dijkstra(graph, zombie_land)

    return answer


print(solution())
๋ฐ˜์‘ํ˜•

'๐Ÿƒ algorithm > boj' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

BOJ 6156 - Cow Contest  (0) 2021.03.08
BOJ 9625 - BABBA  (0) 2021.03.08
BOJ 20055 - ์ปจ๋ฒ ์ด์–ด ๋ฒจํŠธ ์œ„์˜ ๋กœ๋ด‡  (0) 2021.03.08
BOJ 20044 - Project Teams  (0) 2021.03.08
BOJ 1644 - ์†Œ์ˆ˜์˜ ์—ฐ์†ํ•ฉ  (0) 2021.03.08

๐Ÿ’ฌ ๋Œ“๊ธ€