結果

問題 No.860 買い物
ユーザー tktk_snsntktk_snsn
提出日時 2021-01-23 12:32:38
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 943 ms / 1,000 ms
コード長 1,172 bytes
コンパイル時間 467 ms
コンパイル使用メモリ 82,048 KB
実行使用メモリ 104,960 KB
最終ジャッジ日時 2024-12-30 13:09:47
合計ジャッジ時間 10,161 ms
ジャッジサーバーID
(参考情報)
judge1 / judge5
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 15
権限があれば一括ダウンロードができます

ソースコード

diff #

import sys
input = sys.stdin.buffer.readline
sys.setrecursionlimit(10 ** 7)


class UF_tree:
    def __init__(self, n):
        self.root = [-1] * (n + 1)
        self.rank = [0] * (n + 1)

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

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

    def unite(self, x, y):
        x = self.find(x)
        y = self.find(y)
        if x == y:
            return False
        if self.rank[x] < self.rank[y]:
            self.root[y] += self.root[x]
            self.root[x] = y
        else:
            self.root[x] += self.root[y]
            self.root[y] = x
            if self.rank[x] == self.rank[y]:
                self.rank[x] += 1
        return True

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


N = int(input())
ans = 0
edge = []
for i in range(N):
    c, d = map(int, input().split())
    ans += c
    edge.append((c, i, N))
    if i:
        edge.append((d, i, i - 1))
edge.sort()

uf = UF_tree(N + 1)
for c, a, b in edge:
    if uf.unite(a, b):
        ans += c
print(ans)
0