結果

問題 No.101 ぐるぐる!あみだくじ!
ユーザー nebukuro09
提出日時 2016-10-04 11:46:00
言語 Python2
(2.7.18)
結果
AC  
実行時間 26 ms / 5,000 ms
コード長 911 bytes
コンパイル時間 261 ms
コンパイル使用メモリ 6,948 KB
実行使用メモリ 8,192 KB
最終ジャッジ日時 2024-11-21 15:34:37
合計ジャッジ時間 2,523 ms
ジャッジサーバーID
(参考情報)
judge2 / judge3
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 37
権限があれば一括ダウンロードができます

ソースコード

diff #

from fractions import gcd

class UnionFind(object):
    def __init__(self, n):
        self.uf = [-1 for _ in xrange(n)]

    def union(self, x, y):
        x = self.find(x)
        y = self.find(y)
        if x == y:
            return
        if self.uf[x] >= self.uf[y]:
            self.uf[y] += self.uf[x]
            self.uf[x] = y
        else:
            self.uf[x] += self.uf[y]
            self.uf[y] = x

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

N = input()
K = input()
xy = [map(int, raw_input().split()) for _ in xrange(K)]
A = range(N)

for x, y in xy:
    A[x-1], A[y-1] = A[y-1], A[x-1]

uf = UnionFind(N)
for i in xrange(N):
    uf.union(i, A[i])

uf = [abs(u) for u in uf.uf if u<0]
lcm = uf[0]
for i in xrange(1, len(uf)):
    lcm = lcm*uf[i]/gcd(lcm, uf[i])
print lcm
0