結果

問題 No.2289 順列ソート
ユーザー ryomacryomac
提出日時 2023-05-21 18:23:20
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 91 ms / 2,000 ms
コード長 2,092 bytes
コンパイル時間 297 ms
コンパイル使用メモリ 87,304 KB
実行使用メモリ 71,736 KB
最終ジャッジ日時 2023-08-23 15:13:31
合計ジャッジ時間 4,047 ms
ジャッジサーバーID
(参考情報)
judge13 / judge14
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 89 ms
71,324 KB
testcase_01 AC 89 ms
71,324 KB
testcase_02 AC 89 ms
71,600 KB
testcase_03 AC 88 ms
71,440 KB
testcase_04 AC 89 ms
71,556 KB
testcase_05 AC 91 ms
71,492 KB
testcase_06 AC 90 ms
71,508 KB
testcase_07 AC 90 ms
71,584 KB
testcase_08 AC 88 ms
71,644 KB
testcase_09 AC 91 ms
71,672 KB
testcase_10 AC 89 ms
71,216 KB
testcase_11 AC 87 ms
71,692 KB
testcase_12 AC 88 ms
71,248 KB
testcase_13 AC 88 ms
71,496 KB
testcase_14 AC 90 ms
71,664 KB
testcase_15 AC 90 ms
71,376 KB
testcase_16 AC 91 ms
71,508 KB
testcase_17 AC 89 ms
71,464 KB
testcase_18 AC 89 ms
71,508 KB
testcase_19 AC 88 ms
71,512 KB
testcase_20 AC 90 ms
71,736 KB
testcase_21 AC 89 ms
71,492 KB
testcase_22 AC 89 ms
71,672 KB
testcase_23 AC 90 ms
71,432 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

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

from collections import defaultdict


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

    def find(self, x):
        """find(x) は 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):
        """union(x, y) は 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):
        """size(x) は x の属する集合の要素数を返す"""
        return -self.parents[self.find(x)]

    def same(self, x, y):
        """same(x, y) は x と y が同じ集合に属するかを返す"""
        return self.find(x) == self.find(y)

    def members(self, x):
        """members(x) は x の属する集合の要素をリストで返す"""
        root = self.find(x)
        return [i for i in range(self.n) if self.find(i) == root]

    def roots(self):
        """roots() は全ての根の要素をリストで返す"""
        return [i for i, x in enumerate(self.parents) if x < 0]

    def group_count(self):
        """group_count() は集合の数を返す"""
        return len(self.roots())

    def all_group_members(self):
        """d = all_group_members() で {根要素: [そのグループに含まれる要素のリスト], ...} の辞書を返す"""
        group_members = defaultdict(set)
        for member in range(self.n):
            group_members[self.find(member)].add(member)
        return group_members

    def __str__(self):
        """print(uf) での表示用"""
        return "\n".join(f"{r}: {m}" for r, m in self.all_group_members().items())


uf = UnionFind(N + 1)
for i, a in enumerate(A, start=1):
    uf.union(i, a)

k = uf.group_count() - 1
print(N - k)
0