拓扑排序 HDU1285

时间:2021-12-29 06:28:54

这个题是个模板题,可以直接用拓扑排序的模板来做,

AC代码

#include <stdio.h>
#include<iostream>
#include <string.h>
using namespace std;
const int N = ;
int n, m;
int Map[N][N];
int topNum[N];
bool toposort(int *ret)
{
int Indegree[N];
memset(Indegree, , sizeof(Indegree));
int k = ;
for (int i = ; i <= n; i++)
for (int j = ; j <= n; j++)
Indegree[i] += Map[j][i];//计算入度,没有边的时候Map[j][i]为0
for (int i = ; i <= n; i++)
{
for (int j = ; j <= n; j++)
{
if (Indegree[j] == )
{
--Indegree[j];
ret[k++] = j;
for (int t = ; t <= n; t++)
if (Map[j][t])
Indegree[t]--;
break;
}
} }
if (k == n)
return true;
return false;
}
int main()
{
int a, b;
while (cin >> n >> m)
{
memset(Map, , sizeof(Map));
for (int i = ; i < m; i++)
{
cin >> a >> b;
Map[a][b] = ;
}
toposort(topNum);
for (int i = ; i < n; i++)
{
if (i == n - )
printf("%d\n", topNum[i]);
else
printf("%d ", topNum[i]);
}
} return ;
}