結果
問題 | No.101 ぐるぐる!あみだくじ! |
ユーザー |
![]() |
提出日時 | 2022-11-07 11:17:37 |
言語 | Ruby (3.4.1) |
結果 |
AC
|
実行時間 | 104 ms / 5,000 ms |
コード長 | 1,017 bytes |
コンパイル時間 | 45 ms |
コンパイル使用メモリ | 7,552 KB |
実行使用メモリ | 12,160 KB |
最終ジャッジ日時 | 2024-07-20 19:38:25 |
合計ジャッジ時間 | 5,301 ms |
ジャッジサーバーID (参考情報) |
judge1 / judge4 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
sample | AC * 3 |
other | AC * 37 |
コンパイルメッセージ
Syntax OK
ソースコード
class UnionFind def initialize(n) @size = Array.new(n, 1) @rank = Array.new(n, 0) @parent = [] (0..n).each do |i| @parent[i] = i end end def find(x) if @parent[x] == x x else @parent[x] = find(@parent[x]) end end def unite(x, y) x = find(x) y = find(y) return if x == y if @rank[x] < @rank[y] @parent[x] = y @size[y] += @size[x] else @parent[y] = x @size[x] += @size[y] @rank[x] += 1 if @rank[x] == @rank[y] end end def same?(x, y) find(x) == find(y) end def size(x) @size[find(x)] end end N = gets.to_i K = gets.to_i uf = UnionFind.new(N + 1) nums = [*1..N] K.times do x, y = gets.split.map(&:to_i) nums[x - 1], nums[y - 1] = nums[y - 1], nums[x - 1] end nums.each.with_index(1) do |n, i| uf.unite(n, i) end vs = [] checked = Hash.new(false) (1..N).each do |i| x = uf.find(i) next if checked[x] checked[x] = true vs << uf.size(x) end puts vs.inject(:lcm)