목차

레드 블루 스패닝 트리

ps
링크acmicpc.net/…
출처BOJ
문제 번호4792
문제명레드 블루 스패닝 트리
레벨플래티넘 3
분류

최소 신장 트리

시간복잡도O(V^2*α(V))
인풋사이즈V<=1000
사용한 언어Python
제출기록65932KB / 1060ms
최고기록1060ms
해결날짜2021/10/20

풀이

코드

"""Solution code for "BOJ 4792. 레드 블루 스패닝 트리".

- Problem link: https://www.acmicpc.net/problem/4792
- Solution link: http://www.teferi.net/ps/problems/boj/4792

Tags: [MST]
"""

import sys
from teflib import disjointset


def minimum_spanning_tree(node_count, zero_edges, one_edges):
    dsu = disjointset.DisjointSet(node_count)
    component_count, total_cost = node_count, 0
    total_cost = 0
    for edges, cost in ((zero_edges, 0), (one_edges, 1)):
        for u, v in edges:
            try:
                dsu.union(u, v, should_raise=True)
            except ValueError:
                continue
            total_cost += cost
            component_count -= 1
            if component_count == 1:
                return total_cost


def main():
    while True:
        n, m, k = [int(x) for x in sys.stdin.readline().split()]
        if n == 0:
            break
        blue_edges, red_edges = [], []
        for _ in range(m):
            c, f, t = sys.stdin.readline().split()
            if c == 'B':
                blue_edges.append((int(f) - 1, int(t) - 1))
            else:
                red_edges.append((int(f) - 1, int(t) - 1))

        min_blue_count = minimum_spanning_tree(n, red_edges, blue_edges)
        min_red_count = minimum_spanning_tree(n, blue_edges, red_edges)
        max_blue_count = n - 1 - min_red_count
        is_possible = min_blue_count <= k <= max_blue_count
        print('1' if is_possible else '0')


if __name__ == '__main__':
    main()