結果

問題 No.101 ぐるぐる!あみだくじ!
ユーザー ntuda
提出日時 2025-05-01 23:51:56
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 55 ms / 5,000 ms
コード長 692 bytes
コンパイル時間 392 ms
コンパイル使用メモリ 82,220 KB
実行使用メモリ 62,336 KB
最終ジャッジ日時 2025-05-01 23:52:00
合計ジャッジ時間 3,733 ms
ジャッジサーバーID
(参考情報)
judge3 / judge2
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 37
権限があれば一括ダウンロードができます

ソースコード

diff #

from math import lcm

def root(x):
    if P[x] < 0: return x
    P[x] = root(P[x])  # 経路圧縮
    return P[x]

def merge(x,y):
    x = root(x)
    y = root(y)
    if x == y: return
    if x > y: x,y = y,x
    P[x] += P[y]
    P[y] = x

def same(x,y):
    return root(x) == root(y)

def size(x):
    x = root(x)
    return -P[x]


N = int(input())
P = [-1] * N

K = int(input())
A = list(range(N))
for _ in range(K):
    x,y = map(int,input().split())
    x -= 1
    y -= 1
    A[x],A[y] = A[y],A[x]

for i in range(N):
    merge(i,A[i])

ans = 1
checked = set()
for i in range(N):
    x = root(i)
    if x not in checked:
        checked.add(x)
        ans = lcm(ans,size(x))
print(ans)
0