๋ฌธ์
๋ฐฑ์ค ์จ๋ผ์ธ ์ ์ง - 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 |
๐ฌ ๋๊ธ