結果

問題 No.860 買い物
ユーザー roarisroaris
提出日時 2022-10-08 20:33:49
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 691 ms / 1,000 ms
コード長 1,366 bytes
コンパイル時間 882 ms
コンパイル使用メモリ 87,052 KB
実行使用メモリ 119,932 KB
最終ジャッジ日時 2023-09-05 02:06:45
合計ジャッジ時間 8,928 ms
ジャッジサーバーID
(参考情報)
judge12 / judge15
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 76 ms
71,116 KB
testcase_01 AC 75 ms
71,544 KB
testcase_02 AC 74 ms
71,268 KB
testcase_03 AC 75 ms
71,404 KB
testcase_04 AC 76 ms
71,528 KB
testcase_05 AC 77 ms
71,112 KB
testcase_06 AC 151 ms
79,556 KB
testcase_07 AC 623 ms
118,348 KB
testcase_08 AC 624 ms
118,244 KB
testcase_09 AC 616 ms
118,236 KB
testcase_10 AC 610 ms
118,360 KB
testcase_11 AC 280 ms
118,692 KB
testcase_12 AC 307 ms
118,692 KB
testcase_13 AC 597 ms
118,352 KB
testcase_14 AC 691 ms
118,040 KB
testcase_15 AC 363 ms
117,648 KB
testcase_16 AC 583 ms
119,932 KB
testcase_17 AC 257 ms
117,512 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

import sys
input = sys.stdin.readline

class Unionfind:
    def __init__(self, n):
        self.par = [-1]*n
        self.rank = [1]*n
    
    def root(self, x):
        r = x
        
        while not self.par[r]<0:
            r = self.par[r]
        
        t = x
        
        while t!=r:
            tmp = t
            t = self.par[t]
            self.par[tmp] = r
        
        return r
    
    def unite(self, x, y):
        rx = self.root(x)
        ry = self.root(y)
        
        if rx==ry:
            return
        
        if self.rank[rx]<=self.rank[ry]:
            self.par[ry] += self.par[rx]
            self.par[rx] = ry
            
            if self.rank[rx]==self.rank[ry]:
                self.rank[ry] += 1
        else:
            self.par[rx] += self.par[ry]
            self.par[ry] = rx
    
    def is_same(self, x, y):
        return self.root(x)==self.root(y)
    
    def count(self, x):
        return -self.par[self.root(x)]

N = int(input())
CD = [tuple(map(int, input().split())) for _ in range(N)]
edges = []

for v in range(N):
    edges.append((v, N, CD[v][0]))
    
    if v<N-1:
        edges.append((v, v+1, CD[v+1][1]))

edges.sort(key=lambda t: t[2])
uf = Unionfind(N+1)
ans = 0

for u, v, w in edges:
    if not uf.is_same(u, v):
        uf.unite(u, v)
        ans += w

print(ans+sum(C for C, _ in CD))
0