#include #include #include #include using namespace std; typedef vector > Graph; vector tsort(Graph G, int start, int end) { vector ret; int degree[end]; memset(degree, 0, sizeof(degree)); for (int from = start; from < end; from++) { for (int i = 0; i < G[from].size(); i++) { int to = G[from][i]; degree[to]++; } } stack root; for (int i = start; i < end; i++) { if (degree[i] == 0) { root.push(i); } } while (!root.empty()) { int from = root.top(); root.pop(); ret.push_back(from); for (int i = 0; i < G[from].size(); i++) { int to = G[from][i]; degree[to]--; if (degree[to] == 0) { root.push(to); } } } return ret; } int main() { int N, M; cin >> N >> M; Graph G(N); int u, v; for (int i = 0; i < M; ++i) { cin >> u >> v; --u; --v; G[u].push_back(v); } vector res = tsort(G, 0, N); if (res.size() != N) { // tsort failed. cout << -1 << endl; } int K = res.size() - 1; cout << K << endl; for (int i = 0; i < K; ++i) { int a = res[i]; int b = res[i + 1]; cout << a + 1 << " " << b + 1 << endl; } return 0; }