結果
問題 | No.2289 順列ソート |
ユーザー |
![]() |
提出日時 | 2023-05-06 13:33:20 |
言語 | Ruby (3.4.1) |
結果 |
AC
|
実行時間 | 89 ms / 2,000 ms |
コード長 | 923 bytes |
コンパイル時間 | 629 ms |
コンパイル使用メモリ | 7,424 KB |
実行使用メモリ | 12,288 KB |
最終ジャッジ日時 | 2024-11-23 21:40:20 |
合計ジャッジ時間 | 4,005 ms |
ジャッジサーバーID (参考情報) |
judge3 / judge1 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
sample | AC * 3 |
other | AC * 21 |
コンパイルメッセージ
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 P = gets.split.map(&:to_i) uf = UnionFind.new(N + 1) P.each.with_index(1) do |v, i| uf.unite(v, i) end visited = Array.new(N + 1, false) ans = 0 1.upto(N) do |i| x = uf.find(i) next if visited[x] visited[x] = true cnt = uf.size(x) ans += (cnt - 1) end puts ans