結果

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

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 69 ms
71,260 KB
testcase_01 AC 73 ms
71,264 KB
testcase_02 AC 70 ms
71,328 KB
testcase_03 AC 71 ms
71,200 KB
testcase_04 AC 71 ms
71,216 KB
testcase_05 AC 70 ms
71,288 KB
testcase_06 AC 70 ms
71,480 KB
testcase_07 AC 69 ms
71,460 KB
testcase_08 AC 70 ms
71,388 KB
testcase_09 AC 70 ms
71,584 KB
testcase_10 AC 70 ms
71,188 KB
testcase_11 AC 71 ms
71,592 KB
testcase_12 AC 71 ms
71,272 KB
testcase_13 AC 71 ms
71,264 KB
testcase_14 AC 70 ms
71,328 KB
testcase_15 AC 71 ms
71,248 KB
testcase_16 AC 71 ms
71,532 KB
testcase_17 AC 70 ms
71,128 KB
testcase_18 AC 69 ms
71,016 KB
testcase_19 AC 71 ms
71,496 KB
testcase_20 AC 70 ms
71,352 KB
testcase_21 AC 70 ms
71,560 KB
testcase_22 AC 70 ms
71,224 KB
testcase_23 AC 70 ms
71,264 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] * (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 unite(self, x, y):
        x = self.find(x)
        y = self.find(y)
        if x == y:
            return
        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())
p = list(map(int, input().split()))
uf = UnionFind(n)
for i in range(n):
    uf.unite(i, p[i] - 1)
st = set()
ans = 0
for i in range(n):
    i = uf.find(i)
    if i in st:
        continue
    st.add(i)
    ans += 1
print(n - ans)
0