#include using namespace std; const int N = 510; bool g[N][N]; // 邻接矩阵 int in[N]; // 入度 int n, m; // n个顶点,m条边 // 小顶堆 priority_queue, greater> q; /* 4 3 1 2 2 3 4 3 1 2 4 3 */ void toposort() { // 所有入度为零的节点入队列,是拓扑序的起始节点 for (int i = 1; i <= n; i++) if (in[i] == 0) q.push(i); int cnt = 0; while (q.size()) { int u = q.top(); q.pop(); cnt++; // 又一个节点出队列 // 输出拓扑序 if (cnt != n) cout << u << " "; else cout << u << endl; for (int i = 1; i <= n; i++) if (g[u][i]) { in[i]--; if (!in[i]) q.push(i); } } } int main() { while (cin >> n >> m) { memset(g, 0, sizeof g); memset(in, 0, sizeof in); while (m--) { int x, y; cin >> x >> y; if (g[x][y]) continue; // 防止重边 g[x][y] = 1; // 设置有关联关系 in[y]++; // 入度+1 } toposort(); // 拓扑序 } return 0; }