无前驱的顶点的拓扑排序算法,采用链式前向星存储图,队列实现拓扑排序
代码:
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
int i,j,w;
int head[100];
int indegree[100];
struct EdgeNode
{
int to;
int next;
};
EdgeNode Edge[1000];
int n,m;
int main()
{
while(~scanf("%d%d",&n,&m))
{
memset(indegree,0,sizeof(indegree));
memset(head,0,sizeof(head));
for(int k = 1;k <= m;k ++)
{
cin >> i >> j;
indegree[j] ++;
Edge[k].to = j;
Edge[k].next = head[i];
head[i] = k;
}
for(int i = 1;i <= n;i ++)
{
for(int k = head[i];k != 0;k = Edge[k].next)
cout << i << ' ' << j << endl;
}
int queue[100];
int iq = 0;
for(int i = 1;i <= n;i ++)
{
if(indegree[i] == 0)
queue[iq ++] = i;
}
for(int i = 0;i < iq;i ++)
{
for(int k = head[queue[i]];k != 0;k = Edge[k].next)
{
indegree[Edge[k].to] --;
if(indegree[Edge[k].to] == 0)
queue[iq ++] = Edge[k].to;
}
}
for(int i = 0;i < iq;i ++)
cout << queue[i] << ' ';
cout << endl;
}
}