結果

問題 No.2289 順列ソート
ユーザー 👑 H20H20
提出日時 2023-05-19 09:02:12
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 92 ms / 2,000 ms
コード長 1,501 bytes
コンパイル時間 256 ms
コンパイル使用メモリ 87,124 KB
実行使用メモリ 71,864 KB
最終ジャッジ日時 2023-08-22 17:40:35
合計ジャッジ時間 3,919 ms
ジャッジサーバーID
(参考情報)
judge15 / judge12
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 90 ms
71,376 KB
testcase_01 AC 88 ms
71,536 KB
testcase_02 AC 91 ms
71,372 KB
testcase_03 AC 89 ms
71,644 KB
testcase_04 AC 90 ms
71,388 KB
testcase_05 AC 92 ms
71,660 KB
testcase_06 AC 91 ms
71,840 KB
testcase_07 AC 92 ms
71,664 KB
testcase_08 AC 92 ms
71,728 KB
testcase_09 AC 92 ms
71,380 KB
testcase_10 AC 89 ms
71,372 KB
testcase_11 AC 89 ms
71,656 KB
testcase_12 AC 90 ms
71,428 KB
testcase_13 AC 90 ms
71,796 KB
testcase_14 AC 90 ms
71,644 KB
testcase_15 AC 88 ms
71,612 KB
testcase_16 AC 90 ms
71,640 KB
testcase_17 AC 88 ms
71,832 KB
testcase_18 AC 89 ms
71,776 KB
testcase_19 AC 90 ms
71,696 KB
testcase_20 AC 90 ms
71,732 KB
testcase_21 AC 90 ms
71,616 KB
testcase_22 AC 90 ms
71,864 KB
testcase_23 AC 89 ms
71,620 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

from collections import defaultdict


class UnionFind():
    def __init__(self, n):
        self.n = n
        self.parents = [-1] * n

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

    def union(self, x, y):
        x = self.find(x)
        y = self.find(y)

        if x == y:
            return

        if self.parents[x] > self.parents[y]:
            x, y = y, x

        self.parents[x] += self.parents[y]
        self.parents[y] = x

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

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

    def members(self, x):
        root = self.find(x)
        return [i for i in range(self.n) if self.find(i) == root]

    def roots(self):
        return [i for i, x in enumerate(self.parents) if x < 0]

    def group_count(self):
        return len(self.roots())

    def all_group_members(self):
        group_members = defaultdict(set)
        for member in range(self.n):
            group_members[self.find(member)].add(member)
        return group_members

    def __str__(self):
        return '\n'.join(f'{r}: {m}' for r, m in self.all_group_members().items())


N = int(input())
P = list(map(int,input().split()))
uf = UnionFind(N+1)
for i,p in enumerate(P,start=1):
    uf.union(i,p)
GM = uf.all_group_members()
ans = 0
for k,v in GM.items():
    ans+=len(v)-1
print(ans)
0