一道裸的拓扑排序的模板题,只要建好图,下面就按照拓扑排序的正常流程走就可以了。
#include <iostream>
#include <string>
#include <cstring>
#include <queue>
using namespace std;
const int N = 105;
int tot, head[N], in[N];
bool vis[N];
struct Edge{
int next, u, v;
}edge[N];
void add(int u, int v){
edge[tot].u = u;
edge[tot].v = v;
edge[tot].next = head[u];
head[u] = tot ++;
}
int n;
void topsort(){
queue<int> q;
for(int i = 1; i <= n; i ++)
if(in[i] == 0)
q.push(i);
while(q.size()){
int t = q.front();
cout << t << ' ';
q.pop();
for(int i = head[t]; i != -1; i = edge[i].next){
int v = edge[i].v;
in[v] --;
if(!in[v])
q.push(v);
}
}
cout << endl;
}
int main(){
cin >> n;
memset(head, -1, sizeof head);
for(int i = 1; i <= n; i ++){
while(1){
int x;
cin >> x;
if(!x)
break;
in[x] ++;
add(i, x);
}
}
topsort();
return 0;
}