这题肯定是拓扑排序,所以就少了很多判断,参考刘汝佳《入门经典》的代码后再改改就简洁多了。
少了个有向环的判断。
#include <iostream>
#include <cstring>
using namespace std;
int G[101][101],c[101],top[101],top1;
bool dfs(int u,int b)
{
for(int m = 1;m <= b;m++) if(G[u][m])
if(!c[m]) dfs(m,b);
c[u] = 1;
top[top1--] = u;
return true;
}
int main()
{
int a,b;
while(cin >> a >> b && (a || b))
{
int x,y;
top1 = a;
memset(G,0,sizeof(G));
memset(c,0,sizeof(c));
while(b--)
{
cin >> x >> y;
G[x][y] = 1;
}
for(int m = 1;m <= a;m++) if(!c[m])
dfs(m,a);
for(int m = 1;m <= a;m++)
cout << top[m] << ' ';
cout << endl;
}
return 0;
}