結果
問題 | No.1553 Lovely City |
ユーザー |
![]() |
提出日時 | 2021-07-22 10:55:02 |
言語 | Crystal (1.14.0) |
結果 |
AC
|
実行時間 | 301 ms / 2,000 ms |
コード長 | 1,020 bytes |
コンパイル時間 | 11,688 ms |
コンパイル使用メモリ | 296,604 KB |
実行使用メモリ | 50,584 KB |
最終ジャッジ日時 | 2024-07-17 14:37:42 |
合計ジャッジ時間 | 21,252 ms |
ジャッジサーバーID (参考情報) |
judge2 / judge4 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
sample | AC * 2 |
other | AC * 26 |
ソースコード
class DSU def initialize(n) @d = Array(Int32).new(n, -1) end def root(x) @d[x] < 0 ? x : (@d[x] = root(@d[x])) end def unite(x, y) x = root(x) y = root(y) return false if x == y x, y = y, x if @d[x] > @d[y] @d[x] += @d[y] @d[y] = x true end def groups groups = Hash(Int32, Array(Int32)).new { |h, k| h[k] = [] of Int32 } @d.size.times { |i| groups[root(i)] << i } groups.values end end def solve(g, deg, group) a = group.select { |i| deg[i] == 0 } i = 0 while i < a.size g[a[i]].each { |u| a << u if (deg[u] -= 1) == 0 } i += 1 end if group.any? { |i| deg[i] > 0 } a = group + [group[0]] end a.each_cons(2).to_a end n, m = read_line.split.map(&.to_i) g = Array.new(n) { [] of Int32 } deg = [0] * n dsu = DSU.new(n) m.times do u, v = read_line.split.map(&.to_i.pred) g[u] << v deg[v] += 1 dsu.unite(u, v) end ans = dsu.groups.flat_map { |group| solve(g, deg, group) } puts ans.size, ans.join('\n', &.join ' ', &.succ)