#include<iostream>
#include<string.h>
#include<cstdio>
using namespace std;
const int maxn = 1000 + 5;
int a[maxn][maxn];
int c[maxn];
int topo[maxn];
int n, m, t,ans=0;
bool dfs(int u)
{
c[u] = -1;
for(int v=1; v<=n; v++)
{
if(a[u][v])
{
if(c[v] < 0)
return false;
else if(!c[v] && !dfs(v))
return false;
}
}
c[u] = 1;
topo[--t] = u;
return true;
}
bool topo_sort()
{
t = n;
memset(c, 0, sizeof(c));
for(int u=1; u<=n; u++)
{
if(!c[u])
{
if(!dfs(u))
return false;
}
}
return true;
}
int main()
{
int j, k;
while(scanf("%d %d", &n, &m) == 2 && (n || m ))
{
memset(a, 0, sizeof(a));
for(int i=0; i<m; i++)
{
cin >> j >> k;
a[j][k] = 1;
}
if(topo_sort())
{
for(int i=0; i<n; i++)
{
if(i == 0)
cout << topo[i];
else
cout << " " << topo[i];
}
cout << endl;
}
else
cout << "No" << endl;
}
return 0;
}
拓扑排序
最新推荐文章于 2025-05-13 21:35:52 发布