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)