拓扑排序

下图说的很清楚,每次找入度为0的点,将其从序列中删掉,同时与它相连的所有点入度减一;

实现代码,以HUD_1285为例:

#include <iostream>
#include
<cstdio>

using namespace std;
const int N = 501;

int map[N][N];
int into[N], ans[N];

void toposort(int x)
{
int i, j, k;
for(i = 1; i <= x; i++)
for(j = 1; j <= x; j++)
if(map[i][j])
into[j]
++;
into[
0] = 1;
for(i = 1; i <= x; i++)
{
j
= 0;
while(into[j] != 0)
{
j
++;
if(j > x) return ;
}
ans[i]
= j;
into[j]
--;
for(k = 1; k <= x; k++)
if(map[j][k])
into[k]
--;
}
for(i = 1; i <= x; i++)
{
if(x != i) printf("%d ", ans[i]);
else printf("%d\n", ans[i]);
}
}

int main()
{
//freopen("data.in", "r", stdin);
int n, m, i, a, b;
while(~scanf("%d%d", &n, &m))
{
for(i = 1; i <= m; i++)
{
scanf(
"%d%d", &a, &b);
map[a][b]
= 1;
}
topsort(n);
}
return 0;
}
原文地址:https://www.cnblogs.com/vongang/p/2152285.html