結果

問題 No.748 yuki国のお財布事情
ユーザー H3PO4
提出日時 2021-01-05 09:10:39
言語 Python3
(3.13.1 + numpy 2.2.1 + scipy 1.14.1)
結果
TLE  
実行時間 -
コード長 2,059 bytes
コンパイル時間 87 ms
コンパイル使用メモリ 12,544 KB
実行使用メモリ 164,988 KB
最終ジャッジ日時 2024-10-15 16:01:57
合計ジャッジ時間 37,120 ms
ジャッジサーバーID
(参考情報)
judge4 / judge3
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 2 TLE * 1
other AC * 15 WA * 11
権限があれば一括ダウンロードができます

ソースコード

diff #

import sys
from scipy.sparse.csgraph import minimum_spanning_tree
from scipy.sparse import csr_matrix

input = sys.stdin.buffer.readline


class UnionFind:
    def __init__(self, n):
        self.n = n
        self.parent = [i for i in range(n)]
        self.height = [1] * n
        self.size = [1] * n

    def find(self, x):
        if self.parent[x] == x:
            return x
        else:
            self.parent[x] = self.find(self.parent[x])
            return self.parent[x]

    def unite(self, x, y):
        x = self.find(x)
        y = self.find(y)
        if x != y:
            if self.height[x] < self.height[y]:
                self.parent[x] = y
                self.size[y] += self.size[x]
            else:
                self.parent[y] = x
                self.size[x] += self.size[y]
                if self.height[x] == self.height[y]:
                    self.height[x] += 1

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

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

    def group_members(self, x):
        root = self.find(x)
        return [i for i in range(self.n) if self.find(i) == root]

    def roots(self):
        return [i for i, x in enumerate(self.parent) if i == x]

    def group_count(self):
        return len(self.roots())


N, M, K = map(int, input().split())
ABC = []
for _ in range(M):
    a, b, c = map(int, input().split())
    a -= 1
    b -= 1
    ABC.append([a, b, c])

cost = 0

uf = UnionFind(N)
for _ in range(K):
    e = int(input()) - 1
    a, b, c = ABC[e]
    uf.unite(a, b)
    cost += c

compress_dict = {x: i for i, x in enumerate(uf.roots())}
compress_N = uf.group_count()
length, frm, to = [], [], []
for a, b, c in ABC:
    a, b = uf.find(a), uf.find(b)
    if a == b:
        continue
    a, b = compress_dict[a], compress_dict[b]
    length.append(c)
    frm.append(a)
    to.append(b)

matr = csr_matrix((length, (frm, to)), shape=(N, N))
T = minimum_spanning_tree(matr)
cost += int(T.sum())
ans = sum(c for _, _, c in ABC) - cost
print(ans)
0