結果

問題 No.2289 順列ソート
ユーザー rlangevinrlangevin
提出日時 2023-05-05 21:22:11
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 73 ms / 2,000 ms
コード長 1,090 bytes
コンパイル時間 422 ms
コンパイル使用メモリ 87,072 KB
実行使用メモリ 71,480 KB
最終ジャッジ日時 2023-08-15 02:42:38
合計ジャッジ時間 3,096 ms
ジャッジサーバーID
(参考情報)
judge13 / judge11
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 71 ms
71,264 KB
testcase_01 AC 71 ms
71,344 KB
testcase_02 AC 71 ms
71,180 KB
testcase_03 AC 72 ms
71,180 KB
testcase_04 AC 71 ms
71,276 KB
testcase_05 AC 71 ms
71,324 KB
testcase_06 AC 71 ms
71,332 KB
testcase_07 AC 71 ms
71,360 KB
testcase_08 AC 71 ms
71,388 KB
testcase_09 AC 70 ms
71,360 KB
testcase_10 AC 70 ms
71,276 KB
testcase_11 AC 71 ms
71,280 KB
testcase_12 AC 70 ms
71,276 KB
testcase_13 AC 71 ms
71,180 KB
testcase_14 AC 73 ms
71,260 KB
testcase_15 AC 70 ms
71,280 KB
testcase_16 AC 71 ms
71,300 KB
testcase_17 AC 70 ms
71,332 KB
testcase_18 AC 71 ms
71,168 KB
testcase_19 AC 71 ms
71,360 KB
testcase_20 AC 72 ms
71,028 KB
testcase_21 AC 71 ms
71,480 KB
testcase_22 AC 72 ms
71,360 KB
testcase_23 AC 70 ms
71,032 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

import sys

class UnionFind(object):
    def __init__(self, n=1):
        self.par = [i for i in range(n)]
        self.rank = [0 for _ in range(n)]
        self.size = [1 for _ in range(n)]

    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 x != y:
            if self.rank[x] < self.rank[y]:
                x, y = y, x
            if self.rank[x] == self.rank[y]:
                self.rank[x] += 1
            self.par[y] = x
            self.size[x] += self.size[y]

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

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

N = int(input())
P = list(map(int, input().split()))

U = UnionFind(N)
for i in range(N):
    U.union(i, P[i] - 1)
    
ans = 0
S = set()
for i in range(N):
    if U.find(i) not in S:
        S.add(U.find(i))
        ans += U.get_size(i) - 1
print(ans)
    
0