#include #include #include #include #include #include #include #include #include #include #include #include #define debug_value(x) cerr << "line" << __LINE__ << ":<" << __func__ << ">:" << #x << "=" << x << endl; #define debug(x) cerr << "line" << __LINE__ << ":<" << __func__ << ">:" << x << endl; template inline bool chmax(T& a, T b) { if (a < b) { a = b; return 1; } return 0; } template inline bool chmin(T& a, T b) { if (a > b) { a = b; return 1; } return 0; } using namespace std; typedef long long ll; class Scc{ public: int N; vector> G; vector> G_inv; vector idx; Scc(int n){ N = n; G = vector>(n, vector()); G_inv = vector>(n, vector()); used = vector(n, false); idx = vector(n); } void add_edge(int from, int to){ G[from].push_back(to); G_inv[to].push_back(from); } vector> scc(){ vector> ans; for(int i = 0; i < N; i++){ if(!used[i]) dfs1(i); } clear(); int cur = 0; for(int i = vs.size()-1; i >= 0; i--){ if(!used[vs[i]]) { dfs2(vs[i], cur); cur++; ans.push_back(buf); buf.clear(); } } return ans; } private: vector used; vector vs; vector buf; void clear(){ for(int i = 0; i < N; i++) used[i] = false; } void dfs1(int v){ used[v] = true; for(int i = 0; i < G[v].size(); i++){ if(!used[G[v][i]]) dfs1(G[v][i]); } vs.push_back(v); } void dfs2(int v, int k){ used[v] = true; idx[v] = k; for(int i = 0; i < G_inv[v].size(); i++){ if(!used[G_inv[v][i]]) dfs2(G_inv[v][i], k); } buf.push_back(v); } }; struct UnionFind { vector data; UnionFind(int size) : data(size, -1) {} bool unionSet(int x, int y) { x = root(x); y = root(y); if (x != y) { if (data[y] < data[x]) swap(x, y); data[x] += data[y]; data[y] = x; } return x != y; } bool findSet(int x, int y) { return root(x) == root(y); } int root(int x) { return data[x] < 0 ? x : data[x] = root(data[x]); } int size(int x) { return -data[root(x)]; } }; using P = pair; int main(){ ios::sync_with_stdio(false); cin.tie(0); cout << setprecision(10) << fixed; int n, m; cin >> n >> m; vector u(m), v(m); Scc scc(n); UnionFind uf(n); for(int i = 0; i < m; i++){ cin >> u[i] >> v[i]; u[i]--; v[i]--; scc.add_edge(u[i], v[i]); uf.unionSet(u[i], v[i]); } auto v_scc = scc.scc(); vector dag(n, true); vector> components(n); for(auto u: v_scc){ if(u.size() > 1) dag[uf.root(u[0])] = false; for(int x : u){ components[uf.root(x)].push_back(x); } } vector

ans; for(int i = 0; i < n; i++){ if(components[i].size() <= 1) continue; int sz = components[i].size(); for(int j = 0; j < sz-1; j++){ ans.push_back(P(components[i][j], components[i][j+1])); } if(!dag[i]){ ans.push_back(P(components[i][sz-1], components[i][0])); } } cout << ans.size() << endl; for(auto [a, b]: ans) cout << a+1 << ' ' << b+1 << endl; }