from collections import defaultdict, deque class UnionFind: __slots__ = ["n", "parent", "height", "size"] def __init__(self, n): self.n = n self.parent = [i for i in range(n)] self.height = [1] * n self.size = [1] * n def find(self, x): if self.parent[x] == x: return x else: self.parent[x] = self.find(self.parent[x]) return self.parent[x] def unite(self, x, y): x = self.find(x) y = self.find(y) if x != y: if self.height[x] < self.height[y]: self.parent[x] = y self.size[y] += self.size[x] else: self.parent[y] = x self.size[x] += self.size[y] if self.height[x] == self.height[y]: self.height[x] += 1 def issame(self, x, y): return self.find(x) == self.find(y) def group_size(self, x): return self.size[self.find(x)] def group_members(self, x): root = self.find(x) return [i for i in range(self.n) if self.find(i) == root] def roots(self): return [i for i, x in enumerate(self.parent) if i == x] def group_count(self): return len(self.roots()) def topological_sort(nodes, edges): G = {n: [] for n in nodes} deg = {n: 0 for n in nodes} tps = [] for a, b in edges: deg[b] += 1 G[a].append(b) d = deque([i for i, x in deg.items() if not x]) while d: v = d.popleft() tps.append(v) for x in G[v]: deg[x] -= 1 if not deg[x]: d.append(x) if any(deg.values()): return None # not DAG return tps N, M = map(int, input().split()) uf = UnionFind(N) edges = tuple(tuple(int(x) - 1 for x in input().split()) for _ in range(M)) for u, v in edges: uf.unite(u, v) cc_edges = defaultdict(list) cc_nodes = defaultdict(list) for i in range(N): cc_nodes[uf.find(i)].append(i) for u, v in edges: # assert uf.find(u) == uf.find(v) cc_edges[uf.find(u)].append((u, v)) ans = [] for root in uf.roots(): nodes = cc_nodes[root] if len(nodes) == 1: continue edges = cc_edges[root] tps = topological_sort(nodes, edges) if tps is None: # 適当なサイクル for i in range(len(nodes)): j = i + 1 if j == len(nodes): j = 0 ans.append((nodes[i], nodes[j])) else: # DAG for i in range(len(tps) - 1): ans.append((tps[i], tps[i + 1])) print(len(ans)) for u, v in ans: print(u + 1, v + 1)