結果

問題 No.1690 Power Grid
ユーザー H20
提出日時 2021-09-24 22:48:33
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 736 ms / 3,000 ms
コード長 3,373 bytes
コンパイル時間 146 ms
コンパイル使用メモリ 82,348 KB
実行使用メモリ 85,096 KB
最終ジャッジ日時 2024-07-05 11:05:29
合計ジャッジ時間 6,683 ms
ジャッジサーバーID
(参考情報)
judge4 / judge3
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 25
権限があれば一括ダウンロードができます

ソースコード

diff #

import itertools

# UnionFind 参考は以下のサイト
# https://note.nkmk.me/python-union-find/
from collections import defaultdict

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

    def find(self, x):
        if self.parents[x] < 0:
            return x
        else:
            self.parents[x] = self.find(self.parents[x])
            return self.parents[x]

    def union(self, x, y):
        x = self.find(x)
        y = self.find(y)

        if x == y:
            return

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

        self.parents[x] += self.parents[y]
        self.parents[y] = x

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

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

    def 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.parents) if x < 0]

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

    def all_group_members(self):
        group_members = defaultdict(list)
        for member in range(self.n):
            group_members[self.find(member)].append(member)
        return group_members

    def __str__(self):
        return '\n'.join(f'{r}: {m}' for r, m in self.all_group_members().items())




class WarshallFloyd():
    def __init__(self, N):
        self.N = N
        self.d = [[float("inf") for i in range(N)]
                  for i in range(N)]  # d[u][v] : 辺uvのコスト(存在しないときはinf)

    def add(self, u, v, c, directed=False):
        """
        0-indexedであることに注意
        u = from, v = to, c = cost
        directed = Trueなら、有向グラフである
        """
        if directed is False:
            self.d[u][v] = c
            self.d[v][u] = c
        else:
            self.d[u][v] = c

    def WarshallFloyd_search(self):
        # これを d[i][j]: iからjへの最短距離 にする
        # 本来無向グラフでのみ全域木を考えるが、二重辺なら有向でも行けそう
        # d[i][i] < 0 なら、グラフは負のサイクルを持つ
        for k in range(self.N):
            for i in range(self.N):
                for j in range(self.N):
                    self.d[i][j] = min(
                        self.d[i][j], self.d[i][k] + self.d[k][j])
        hasNegativeCycle = False
        for i in range(self.N):
            if self.d[i][i] < 0:
                hasNegativeCycle = True
                break
        for i in range(self.N):
            self.d[i][i] = 0
        return hasNegativeCycle, self.d

N,M,K = map(int, input().split())
A = list(map(int, input().split()))
XYZ = [list(map(int, input().split())) for i in range(M)]
graph = WarshallFloyd(N)
for x, y, z in XYZ:
    graph.add(x-1, y-1, z)
ans = 10**20
hasNegativeCycle, d = graph.WarshallFloyd_search()

for C in list(itertools.combinations(list(range(N)), K)):
    temp = 0
    for c in C:
        temp+=A[c]
    L = []
    for p1,p2 in list(itertools.combinations(C, 2)):
        L.append([p1,p2,d[p1][p2]])
    L = sorted(L, key=lambda x: x[2])
    uf = UnionFind(N)
    for p1,p2,t in L:
        if not uf.same(p1,p2):
            uf.union(p1,p2)
            temp+=t
    ans = min(temp,ans)
print(ans)

0