AOJ GRL_2_A Minimum Spanning Tree
備忘録
問題
http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=GRL_2_A&lang=ja
回答
import sys, os, math, bisect, itertools, collections, heapq, queue, copy, array # from scipy.sparse.csgraph import csgraph_from_dense, floyd_warshall # from decimal import Decimal # from collections import defaultdict, deque sys.setrecursionlimit(10000000) ii = lambda: int(sys.stdin.buffer.readline().rstrip()) il = lambda: list(map(int, sys.stdin.buffer.readline().split())) fl = lambda: list(map(float, sys.stdin.buffer.readline().split())) iln = lambda n: [int(sys.stdin.buffer.readline().rstrip()) for _ in range(n)] iss = lambda: sys.stdin.buffer.readline().decode().rstrip() sl = lambda: list(map(str, sys.stdin.buffer.readline().decode().split())) isn = lambda n: [sys.stdin.buffer.readline().decode().rstrip() for _ in range(n)] lcm = lambda x, y: (x * y) // math.gcd(x, y) MOD = 10 ** 9 + 7 INF = float('inf') class UnionFind: def __init__(self, N): self.tree = [-1 for _ in range(N)] def root(self, N): if self.tree[N] < 0: return N self.tree[N] = self.root(self.tree[N]) return self.tree[N] def same(self, x, y): return self.root(x) == self.root(y) def unite(self, x, y): x = self.root(x) y = self.root(y) if x == y: return if self.tree[x] > self.tree[y]: x, y = y, x self.tree[x] += self.tree[y] self.tree[y] = x def size(self, x): return -self.tree[self.root(x)] def main(): if os.getenv("LOCAL"): sys.stdin = open("input.txt", "r") V, E = il() uf = UnionFind(V) G = [] for e in range(E): s, t, w = il() G.append((w, s, t)) G.sort() ret = 0 for w, s, t in G: if not uf.same(s, t): ret += w uf.unite(s, t) print(ret) if __name__ == '__main__': main()
考え方
螺旋本より、最小全域木を求める問題。
UnionFind木を用いてグラフに閉路を作らないようにクラスカル法でグラフを作る。
類似問題:ARC076 D - Built?
予め、入力のグラフの辺を重みでソートし、
重みの小さい順にグラフを構成していく。
各辺はUnionFindでルートの頂点が同じか否か(辺を繋げたときに閉路になるか)を判定し、
異なる場合に結合を行う。