classgraph { private: linkedList arr[maxN]; int inDeg[maxN]; intsize; public: graph() { size = 0; } graph(int n) { size = n; setIN(); } ~graph() { } voidsetIN(){ for (int i = 0; i <= size; i++) inDeg[i] = 0; } voidadd(int p1, int p2){ arr[p1].add(p2); inDeg[p2]++; } vector<int> topoSort(){ priority_queue<int, vector<int>, greater<int>> q; vector<int> ans; for (int i = 1; i <= size; i++) if (inDeg[i] == 0) q.push(i);//所有入度为零的点入队 while (!q.empty()) { int x = q.top();//选出队首元素 开始遍历 q.pop(); ans.push_back(x); for (node* p = arr[x].getHeader(); p != NULL; p = p->next) { int ele = p->ele; inDeg[ele]--;//与之相邻的点入度 -1 if (inDeg[ele] == 0)//入度为零 可入队 q.push(ele); } } return ans; } };
intmain(){ int n, m; while (!(cin >> n >> m).eof()) { graph G(n); for (int i = 0; i < m; i++) { int p1, p2; cin >> p1 >> p2; G.add(p1, p2); } vector<int> v = G.topoSort(); for (int i = 0; i < v.size() - 1; i++) cout << v[i] << " "; cout << v[v.size() - 1] << endl; }