[BaekJoon] 15591๋ฒˆ : MooTube

Updated:

15591๋ฒˆ : MooTube


๋ฌธ์ œ๊ฐ€ ๋ณต์žกํ•ด์„œ ์ฝ๋Š”๋ฐ๋งŒ ์‹œ๊ฐ„์ด ์˜ค๋ž˜ ๊ฑธ๋ ธ๋‹ค..

์ฃผ์ ˆ์ฃผ์ ˆ ๊ธธ์ง€๋งŒ ์ •๋ฆฌ ํ•ด๋ณด์ž๋ฉด [1, 2] ๊ฐ€ ์ฃผ์–ด์ง€๋Š” ๊ฒฝ์šฐ 2๋ฒˆ ๋…ธ๋“œ์—์„œ ์œ ์‚ฌ๋„๊ฐ€ 1 ์ด์ƒ์ธ ๋ชจ๋“  ๋…ธ๋“œ์˜ ๊ฐœ์ˆ˜๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค.

์œ ์‚ฌ๋„๋Š” A ๋…ธ๋“œ์™€ B ๋…ธ๋“œ๋ฅผ ์ž‡๋Š” ๊ฐ„์„  ์ค‘ ๊ฐ€์žฅ ์ž‘์€ ๊ฐ„์„ ์˜ ๋ฌด๊ฒŒ๋ฅผ ๊ฐ€์ง€๊ฒŒ ๋œ๋‹ค.

image

๋งŒ์•ฝ ์ด๋ ‡๊ฒŒ ์ƒ๊ธด ๊ทธ๋ž˜ํ”„๊ฐ€ ์žˆ๋Š” ๊ฒฝ์šฐ 1๊ณผ 3์˜ ์œ ์‚ฌ๋„๋Š” 2๊ฐ€ ๋œ๋‹ค.

1๊ณผ 3์„ ์ž‡๋Š” ๊ฐ„์„  ์ค‘ ๊ฐ€์žฅ ์ž‘์€ ๊ฐ„์„ ์˜ ๋ฌด๊ฒŒ๋Š” 2์ด๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค.

๋งˆ์ฐฌ๊ฐ€์ง€๋กœ 1๊ณผ 4์˜ ์œ ์‚ฌ๋„๋Š” 3์ด ๋œ๋‹ค.

๋…ธ๋“œ๊ฐ„ ์œ ์‚ฌ๋„๋ฅผ ๊ตฌํ•˜๋Š” ๋ฐฉ๋ฒ•์€ ๋…ธ๋“œ๊ฐ„ ๊ฑฐ๋ฆฌ๋ฅผ ๊ตฌํ•˜๋Š” ๋ฐฉ๋ฒ•์„ ์•ฝ๊ฐ„ ๋ณ€ํ˜•ํ•˜๋ฉด ๋œ๋‹ค.

์˜ˆ๋ฅผ ๋“ค์–ด 1๊ณผ 4์˜ ๊ฑฐ๋ฆฌ๋ฅผ ๊ตฌํ•˜๊ณ  ์‹ถ์€ ๊ฒฝ์šฐ 3 + 4 ์˜ ๊ณ„์‚ฐ์„ ํ•˜๊ฒŒ ๋œ๋‹ค.

์ด๋•Œ ๋”ํ•˜๊ธฐ ๊ณ„์‚ฐ์„ ํ•˜์ง€ ๋ง๊ณ  ๊ฑฐ๋ฆฌ๋ฅผ ์ตœ์†Ÿ๊ฐ’์œผ๋กœ ๊ฐฑ์‹  ํ•ด์ฃผ๋ฉด ๋œ๋‹ค.


import sys
from collections import deque


def BFS(N, graph, k, start):
	visit = [False] * (N + 1)
	queue = deque([[start, float('inf')]])
	visit[start] = True

	answer = 0
	while queue:
		node, USADO = queue.popleft()
		for i in graph[node]:
			visit_node, visit_USADO = i

			min_USADO = min(USADO, visit_USADO)
			if not visit[visit_node] and min_USADO >= k:
				answer += 1
				visit[visit_node] = True
				queue.append([visit_node, min_USADO])

	return answer


if __name__ == "__main__":
	N, Q = map(int, input().split())
	graph = {i + 1: [] for i in range(N)}

	for _ in range(N - 1):
		start, end, USADO = map(int, sys.stdin.readline().rsplit())
		graph[start].append([end, USADO])
		graph[end].append([start, USADO])

	for _ in range(Q):
		k, check = map(int, sys.stdin.readline().rsplit())
		print(BFS(N, graph, k, check))



Categories:

Updated:

Leave a comment