목차

완전그래프의 최소 스패닝 트리

ps
링크acmicpc.net/…
출처BOJ
문제 번호20390
문제명완전그래프의 최소 스패닝 트리
레벨골드 2
분류

최소 신장 트리

시간복잡도O(n^2)
인풋사이즈n<=10000
사용한 언어Python
제출기록31024KB / 14260ms
최고기록14260ms
해결날짜2021/10/24

풀이

코드

코드 1 - 일반 버전. (python에서는 TLE)

"""Solution code for "BOJ 20390. 완전그래프의 최소 스패닝 트리".

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

Tags: [MST]

This code should be submitted with PyPy3. It gets TLE with Python3.
"""

from teflib import tgraph


def main():

    def weight_func(u, v):
        t = x_a[u] + x_b[v] if u < v else x_a[v] + x_b[u]
        return (t if t < C else t - C) ^ D

    N = int(input())
    A, B, C, D = [int(x) for x in input().split()]
    X = [int(x) for x in input().split()]

    x_a = [x * A % C for x in X]
    x_b = [x * B % C for x in X]

    print(tgraph.prim_mst(N, weight_func))


if __name__ == '__main__':
    main()

코드 2 - 최적화 버전. (python에서도 AC)

"""Solution code for "BOJ 20390. 완전그래프의 최소 스패닝 트리".

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

Tags: [MST]
"""

INF = float('inf')


def main():
    N = int(input())
    A, B, C, D = [int(x) for x in input().split()]
    X = [int(x) for x in input().split()]

    x_a = [x * A % C for x in X]
    x_b = [x * B % C for x in X]
    weights = {x: INF for x in range(1, N)}
    u = 0
    total_weight = 0
    for _ in range(N - 1):
        min_weight_node, min_weight = None, INF
        x_a_u, x_b_u = x_a[u], x_b[u]
        for v, weight_v in weights.items():
            t = x_a_u + x_b[v] if u < v else x_a[v] + x_b_u
            w = (t if t < C else t - C) ^ D
            if w < weight_v:
                weight_v = weights[v] = w
            if weight_v < min_weight:
                min_weight_node, min_weight = v, weight_v
        u = min_weight_node
        total_weight += min_weight
        del weights[u]
    print(total_weight)


if __name__ == '__main__':
    main()