ps | |
---|---|
링크 | acmicpc.net/… |
출처 | BOJ |
문제 번호 | 20390 |
문제명 | 완전그래프의 최소 스패닝 트리 |
레벨 | 골드 2 |
분류 |
최소 신장 트리 |
시간복잡도 | O(n^2) |
인풋사이즈 | n<=10000 |
사용한 언어 | Python |
제출기록 | 31024KB / 14260ms |
최고기록 | 14260ms |
해결날짜 | 2021/10/24 |
"""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()
"""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()