#include #include #include #include #include #include #include #include #include #include #define mkp make_pair #define mkt make_tuple #define rep(i, n) for (int i = 0; i < (n); ++i) #define all(v) v.begin(), v.end() using namespace std; typedef long long ll; const ll MOD = 1e9 + 7; // const ll MOD = 998244353; template void chmin(T &a, const T &b) { if (a > b) a = b; } template void chmax(T &a, const T &b) { if (a < b) a = b; } class DisjointSet { public: int N; vector rank, p; vector sz; DisjointSet() {} DisjointSet(int n) : N(n), rank(n), p(n), sz(n) { for (int i = 0; i < N; i++) makeSet(i); } void makeSet(int x) { p[x] = x; rank[x] = 0; sz[x] = 1; } bool same(int x, int y) { return leader(x) == leader(y); } void unite(int x, int y) { if (same(x, y)) return; link(leader(x), leader(y)); } void link(int x, int y) { if (rank[x] > rank[y]) swap(x, y); p[x] = y; sz[y] += sz[x]; if (rank[x] == rank[y]) { ++rank[y]; } } int leader(int x) { if (x != p[x]) p[x] = leader(p[x]); return p[x]; } int size(int x) { return sz[leader(x)]; } }; void solve() { int N, M; cin >> N >> M; vector U(M), V(M); rep(i, M) cin >> U[i] >> V[i]; rep(i, M) { U[i]--; V[i]--; } vector> g(N); rep(i, M) g[U[i]].push_back(V[i]); DisjointSet us(N); rep(i, M) us.unite(U[i], V[i]); vector> nodes(N); rep(i, N) nodes[us.leader(i)].push_back(i); vector> e_idxs(N); rep(i, M) e_idxs[us.leader(U[i])].push_back(i); vector in(N, 0); vector> output; for (int k = 0; k < N; k++) { if (nodes[k].empty()) continue; for (auto ed : e_idxs[k]) in[V[ed]]++; queue Q; for (auto id : nodes[k]) if (in[id] == 0) Q.push(id); vector order; while (!Q.empty()) { auto now = Q.front(); Q.pop(); order.push_back(now); for (auto nex : g[now]) { in[nex]--; if (in[nex] == 0) Q.push(nex); } } if (order.size() == nodes[k].size()) { for (int i = 0; i + 1 < order.size(); i++) output.emplace_back(order[i], order[i + 1]); } else { rep(i, nodes[k].size()) output.emplace_back(nodes[k][i], nodes[k][(i + 1) % (int)nodes[k].size()]); } } cout << output.size() << "\n"; for (auto [a, b] : output) cout << a + 1 << " " << b + 1 << "\n"; } int main() { cin.tie(nullptr); ios::sync_with_stdio(false); solve(); return 0; }