对于拓扑排序,每次能入队的只有入度为0的点,所以用优先队列即可。
以及,第一组数据日常卡OJ,这组数据跳了一个点,我的程序这个版本也过不了(其实写了另一个版的),稍微改改更正确。
#include <bits/stdc++.h>
using namespace std;
const int maxn=510;
vector<int> vec[maxn];
int indeg[maxn],seq[maxn],N,M,tot=0;
void topo()
{
tot=0;
priority_queue<int,vector<int>,greater<int> > pq;
for (int i=1;i<=N;i++) {
if (indeg[i]==0) {
pq.push(i);
}
}
while (!pq.empty()) {
int u=pq.top();
pq.pop();
seq[tot++]=u;
for (int i=0;i<vec[u].size();i++) {
if (--indeg[vec[u][i]]==0) {
pq.push(vec[u][i]);
}
}
}
}
int main()
{
while (scanf("%d%d",&N,&M)!=EOF) {
for (int i=0;i<=N;i++) {
vec[i].clear();
}
memset(indeg,0,sizeof(indeg));
int x,y;
for (int i=0;i<M;i++) {
scanf("%d%d",&x,&y);
vec[x].push_back(y);
indeg[y]++;
}
topo();
for (int i=0;i<tot-1;i++) {
printf("%d ",seq[i]);
}
printf("%d
",seq[tot-1]);
}
return 0;
}
/*
8 6
1 7
2 4
3 5
7 8
4 8
5 8
7 6
1 2
2 3
3 4
6 2
5 3
7 5
*/