给出一个图的结构,输出其拓扑排序序列,要求在同等条件下,编号小的顶点在前。
Input
若干行整数,第一行有2个数,分别为顶点数v和弧数a,接下来有a行,每一行有2个数,分别是该条弧所关联的两个顶点编号。
v<=100, a<=500
Output
若干个空格隔开的顶点构成的序列(用小写字母)。
Sample Input
6 8
1 2
1 3
1 4
3 2
3 5
4 5
6 4
6 5
Sample Output
v1 v3 v2 v6 v4 v5
在输入时记录每一个的度,然后通过度为0,不断存储,不断的减度;
#include <bits/stdc++.h>
using namespace std;
const int maxn = 100+5;
int Map[maxn][maxn];
int rudu[maxn];
int path[maxn];
int n,m;
void topsort()
{
for(int i = 1; i <= n; i++)
for(int j = 1; j <= n; j++)
if(Map[i][j] == 1)
rudu[j]++;//表示到第j有多少个前提;
for(int i = 1; i <= n; i++)
{
int item = 0;
for(int j = 1; j <= n; j++)
if(rudu[j]==0)//表示到达该点的前提没了
{
item = j;
break;
}
rudu[item] = -1; //更新为-1
path[i] = item;
for(int j = 1; j <= n; j++)
if(Map[item][j] == 1)
rudu[j]--;
}
}
int main()
{
while(scanf("%d%d",&n,&m)==2)
{
int a,b;
memset(Map,0,sizeof Map);
memset(rudu,0,sizeof rudu);
memset(path,0,sizeof path);
for(int i = 1; i <= m; i++)
{
scanf("%d %d",&a,&b);
Map[a][b] = 1;//表示a->b的一个关系;
}
topsort();
for(int i = 1; i < n; i++)
printf("v%d ",path[i]);
printf("v%d\n",path[n]);
}
return 0;
}