結果

問題 No.3650 Teleportation Cycles
コンテスト
ユーザー Rino-program
提出日時 2026-07-19 16:43:35
言語 PyPy3
(7.3.23 + ACL)
コンパイル:
pypy3 -mpy_compile _filename_
実行:
pypy3 _filename_
結果
AC  
実行時間 211 ms / 2,000 ms
+ 91µs
コード長 1,283 bytes
記録
記録タグの例:
初AC ショートコード 純ショートコード 純主流ショートコード 最速実行時間
コンパイル時間 247 ms
コンパイル使用メモリ 95,988 KB
実行使用メモリ 112,128 KB
最終ジャッジ日時 2026-08-28 20:50:24
合計ジャッジ時間 6,509 ms
ジャッジサーバーID
(参考情報)
judge3_0 / judge1_0
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 36
権限があれば一括ダウンロードができます

ソースコード

diff #
raw source code

import sys

# 再帰呼び出しの上限を増やす
sys.setrecursionlimit(300000)

def main():
    # 入力の高速化
    input = sys.stdin.read
    data = input().split()
    N = int(data[0])
    A = [0] * (N + 1)
    for i in range(1, N + 1):
        A[i] = int(data[i])

    # DSU クラスの実装
    class DSU:
        def __init__(self, n):
            self.parent_or_size = [-1] * n

        def leader(self, a):
            if self.parent_or_size[a] < 0:
                return a
            self.parent_or_size[a] = self.leader(self.parent_or_size[a])
            return self.parent_or_size[a]

        def same(self, a, b):
            return self.leader(a) == self.leader(b)

        def merge(self, a, b):
            x, y = self.leader(a), self.leader(b)
            if x == y:
                return False
            if -self.parent_or_size[x] < -self.parent_or_size[y]:
                x, y = y, x
            self.parent_or_size[x] += self.parent_or_size[y]
            self.parent_or_size[y] = x
            return True

    dsu = DSU(N + 1)
    cycle_count = 0

    for i in range(1, N + 1):
        if dsu.same(i, A[i]):
            cycle_count += 1
        else:
            dsu.merge(i, A[i])

    print(cycle_count)

if __name__ == '__main__':
    main()
0