結果

問題 No.860 買い物
ユーザー stngstng
提出日時 2022-07-30 13:11:37
言語 PyPy3
(7.3.15)
結果
TLE  
実行時間 -
コード長 1,311 bytes
コンパイル時間 274 ms
コンパイル使用メモリ 86,976 KB
実行使用メモリ 124,816 KB
最終ジャッジ日時 2023-09-27 15:39:22
合計ジャッジ時間 10,466 ms
ジャッジサーバーID
(参考情報)
judge12 / judge13
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 72 ms
71,264 KB
testcase_01 AC 73 ms
71,380 KB
testcase_02 AC 73 ms
71,416 KB
testcase_03 AC 73 ms
71,388 KB
testcase_04 AC 73 ms
71,268 KB
testcase_05 AC 74 ms
71,408 KB
testcase_06 AC 176 ms
79,676 KB
testcase_07 AC 970 ms
124,076 KB
testcase_08 AC 987 ms
124,816 KB
testcase_09 AC 955 ms
120,620 KB
testcase_10 AC 971 ms
123,040 KB
testcase_11 AC 404 ms
117,536 KB
testcase_12 AC 399 ms
117,520 KB
testcase_13 AC 857 ms
120,692 KB
testcase_14 TLE -
testcase_15 AC 524 ms
117,156 KB
testcase_16 AC 962 ms
124,504 KB
testcase_17 AC 411 ms
120,888 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

class UnionFind:
    def __init__(self, n):
        self.par = [i for i in range(n+1)]
        self.rank = [0] * (n+1)
        self.size = [1 for _ in range(n+1)]
    # 検索
    def find(self, x):
        if self.par[x] == x:
            return x
        else:
            self.par[x] = self.find(self.par[x])
            return self.par[x]
    # 併合
    def union(self, x, y):
        x = self.find(x)
        y = self.find(y)
        if self.rank[x] < self.rank[y]:
            self.par[x] = y
            self.size[y] += self.size[x]
        else:
            self.par[y] = x
            self.size[x] += self.size[y]
        if self.rank[x] == self.rank[y]:
            self.rank[x] += 1
    # 同じ集合に属するか判定
    def same_check(self, x, y):
        return self.find(x) == self.find(y)

n = int(input())
cd = [[int(i) for i in input().split()] for j in range(n)]

c = []
ans = 0

for i in range(n):
    c.append([cd[i][0],n,i])
    if i != 0:
        c.append([cd[i][1],0,i-1])
    ans += cd[i][0]

ki = UnionFind(n+2)
c.sort()
for i in range(2*n-1):
    cost,tmp,v = c[i]
    if tmp == n:
        if not ki.same_check(n,v):
            ki.union(n,v)
            ans += cost
    else:
        if not ki.same_check(v,v+1):
            ki.union(v+1,v)
            ans += cost

print(ans)
0