拓扑排序
拓扑排序算法
#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;
int n, m, t;
const int maxn = 100 + 9;
bool g[maxn][maxn];
int c[maxn], topo[maxn];
void dfs(int u)
{
c[u] = -1;
for (int v = 1; v <= n; v++)
if (g[u][v] && !c[v]) dfs(v);
c[u] = 1;
topo[--t] = u;
}
void solve()
{
memset(g, 0, sizeof(g));
memset(c, 0, sizeof(c));
memset(topo, 0, sizeof(topo));
for (int i = 0; i < m; i++)
{
int x, y;
cin >> x >> y;
g[x][y] = true;
}
t = n;
for (int u = 1; u <= n; u++)
if (!c[u]) dfs(u);
cout << topo[0];
for (int i = 1; i < n; i++)
cout << ' ' << topo[i];
cout << endl;
}
int main()
{
// freopen("input.txt", "r", stdin);
for (;;)
{
cin >> n >> m;
if (n == 0 && m == 0) break;
solve();
}
}