結果

問題 No.1553 Lovely City
ユーザー yuruhiyayuruhiya
提出日時 2021-07-22 10:55:02
言語 Crystal
(1.11.2)
結果
AC  
実行時間 287 ms / 2,000 ms
コード長 1,020 bytes
コンパイル時間 18,986 ms
コンパイル使用メモリ 259,352 KB
実行使用メモリ 58,644 KB
最終ジャッジ日時 2023-09-24 13:50:36
合計ジャッジ時間 28,540 ms
ジャッジサーバーID
(参考情報)
judge12 / judge11
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 3 ms
4,392 KB
testcase_01 AC 3 ms
4,380 KB
testcase_02 AC 99 ms
40,568 KB
testcase_03 AC 3 ms
4,528 KB
testcase_04 AC 3 ms
4,744 KB
testcase_05 AC 3 ms
4,844 KB
testcase_06 AC 3 ms
4,516 KB
testcase_07 AC 3 ms
4,496 KB
testcase_08 AC 176 ms
30,684 KB
testcase_09 AC 194 ms
31,996 KB
testcase_10 AC 212 ms
48,132 KB
testcase_11 AC 145 ms
28,656 KB
testcase_12 AC 226 ms
53,964 KB
testcase_13 AC 166 ms
28,284 KB
testcase_14 AC 182 ms
31,220 KB
testcase_15 AC 164 ms
34,460 KB
testcase_16 AC 205 ms
33,104 KB
testcase_17 AC 155 ms
36,532 KB
testcase_18 AC 282 ms
58,596 KB
testcase_19 AC 282 ms
58,644 KB
testcase_20 AC 276 ms
57,640 KB
testcase_21 AC 285 ms
57,340 KB
testcase_22 AC 277 ms
57,264 KB
testcase_23 AC 276 ms
58,184 KB
testcase_24 AC 279 ms
58,188 KB
testcase_25 AC 287 ms
57,692 KB
testcase_26 AC 283 ms
57,744 KB
testcase_27 AC 281 ms
58,324 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

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)
0