拓扑排序要解决的问题是给一个有向无环图的所有节点排序。
如图,就是先找到入度为0的点,找到与期所连接的边,去除边即2、3入读减一,再把入读为0的点加入队列,重复操作,直到最后。
#include<bits/stdc++.h>
using namespace std;
#define IOS ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
#define ll long long
const int N = 1e4;
int input[N];
vector<int>p[N];
int n;
void toposort() {
vector<int>v;
queue<int>q;
for(int i = 1; i <= n; i++) {
if(input[i] == 0)
q.push(i),v.push_back(i);
}
while(!q.empty()) {
int top = q.front();
q.pop();
int len = p[top].size();
for(int i = 0; i < len; i++) {
int now = p[top][i];
input[now]--;
if(input[now] == 0)
q.push(now),v.push_back(now);
}
}
for(auto it : v)
cout << it << " ";
}
int main( ) {
cin >> n;
for(int i = 1; i <= n; i++) {
while(1) {
int x;
cin >> x;
if(x == 0) break;
else p[i].push_back(x),input[x]++;
}
}
toposort();
return 0;
}