Library-Python

This documentation is automatically generated by online-judge-tools/verification-helper

View the Project on GitHub Rin204/Library-Python

Kruskal
(expansion/tree/Kruskal.py)

概要

最小全域木の重み総和を求めます.

$edges = [(from1, to1, cost1), (from2, to2, cost2), …)]$の形式で辺情報を与えてください

使い方

cost = Kruskal(n, edges, is_sorted=False)

全体が連結でない場合は -1 を返します.

Code

class UnionFind:
    def __init__(self, n):
        self.n = n
        self.par = [-1] * n
        self.group_ = n

    def find(self, x):
        if self.par[x] < 0:
            return x
        lst = []
        while self.par[x] >= 0:
            lst.append(x)
            x = self.par[x]
        for y in lst:
            self.par[y] = x
        return x

    def unite(self, x, y):
        x = self.find(x)
        y = self.find(y)
        if x == y:
            return False

        if self.par[x] > self.par[y]:
            x, y = y, x

        self.par[x] += self.par[y]
        self.par[y] = x
        self.group_ -= 1
        return True

    def size(self, x):
        return -self.par[self.find(x)]

    def same(self, x, y):
        return self.find(x) == self.find(y)

    @property
    def group(self):
        return self.group_


def Kruskal(n, edges, is_sorted=False):
    if n == 1:
        return 0
    if not is_sorted:
        edges.sort(key=lambda x: x[2])
    UF = UnionFind(n)
    res = 0
    for u, v, cost in edges:
        if UF.unite(u, v):
            res += cost
            if UF.group == 1:
                return res
    return -1
Traceback (most recent call last):
  File "/opt/hostedtoolcache/Python/3.11.4/x64/lib/python3.11/site-packages/onlinejudge_verify/documentation/build.py", line 81, in _render_source_code_stat
    bundled_code = language.bundle(
                   ^^^^^^^^^^^^^^^^
  File "/opt/hostedtoolcache/Python/3.11.4/x64/lib/python3.11/site-packages/onlinejudge_verify/languages/python.py", line 108, in bundle
    raise NotImplementedError
NotImplementedError
Back to top page