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

BOJ 1240 - ๋…ธ๋“œ์‚ฌ์ด์˜ ๊ฑฐ๋ฆฌ

by HandHand 2021. 6. 7.

๋ฌธ์ œ

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

ํ’€์ด ๊ณผ์ •

ํŠธ๋ฆฌ ๋Š” ํŠน์ • ์ •์ ์—์„œ ๋‹ค๋ฅธ ์ •์ ๊นŒ์ง€ ๋‹จ ํ•˜๋‚˜์˜ ๊ฒฝ๋กœ๊ฐ€ ์กด์žฌํ•ฉ๋‹ˆ๋‹ค.
๋”ฐ๋ผ์„œ BFS ๋ฅผ ์ด์šฉํ•ด ๊ฐ ์ •์ ๊นŒ์ง€์˜ ๊ฑฐ๋ฆฌ๋ฅผ ๊ตฌํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
์ด๋•Œ ์ธ์ ‘ ๋ฆฌ์ŠคํŠธ๋ฅผ ์ด์šฉํ•ด์„œ ๊ทธ๋ž˜ํ”„๋ฅผ ๊ตฌํ˜„ํ•œ๋‹ค๋ฉด O(V+E) ์˜ ์‹œ๊ฐ„ ๋ณต์žก๋„๋กœ ๋ฌธ์ œ๋ฅผ ํ•ด๊ฒฐํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

์ฝ”๋“œ


import sys
from collections import deque


def make_graph(edges):
    graph = {n + 1: [] for n in range(N)}

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

    return graph


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

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

    while q:
        here, acc_cost = q.popleft()
        if here == goal:
            return acc_cost

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


def solution(frm, to):
    return bfs(frm, to)


if __name__ == '__main__':
    N, M = list(map(int, sys.stdin.readline().split()))
    edges = [list(map(int, sys.stdin.readline().split())) for _ in range(N - 1)]
    pairs = [list(map(int, sys.stdin.readline().split())) for _ in range(M)]

    graph = make_graph(edges)

    for frm, to in pairs:
        answer = solution(frm, to)
        print(answer)

๋ฐ˜์‘ํ˜•

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

BOJ 4811 - ์•Œ์•ฝ  (0) 2021.06.07
BOJ 5980 - Corn Maze  (0) 2021.06.07
BOJ 11265 - ๋๋‚˜์ง€ ์•Š๋Š” ํŒŒํ‹ฐ  (0) 2021.06.04
BOJ 10472 - ์‹ญ์ž๋’ค์ง‘๊ธฐ  (0) 2021.04.18
BOJ 13908 - ๋น„๋ฐ€๋ฒˆํ˜ธ  (0) 2021.04.13

๐Ÿ’ฌ ๋Œ“๊ธ€