版权声明:Andy https://blog.csdn.net/Alibaba_lhl/article/details/81415178
Sample Input
5 4
1 2
2 3
1 3
1 5
0 0
Sample Output
1 4 2 5 3
AC Code
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <vector>
#include <string>
#include <map>
#include <set>
#include <stack>
#include <queue>
#include <functional>
#include <algorithm>
#define _USE_MATH_DEFINES
using namespace std;
typedef long long ll;
const int MAXN = 1e3+5;
int n, m;
int p[MAXN][MAXN];
int vis[MAXN];
int b[MAXN];
void topsort()
{
for(int i=1; i<=n; )
{
int w = 0;
for(int j=1; j<=n; j++)
{
if(!vis[j])
{
vis[j]--;
b[++w] = j;
if(i==1) printf("%d",j);
else printf(" %d",j);
i++;
}
}
for(int u = 1; u<=w; u++)
{
for(int k=1; k<=n; k++)
{
if(p[b[u]][k]) vis[k]--;
}
}
}
printf("\n");
}
int main()
{
while(~scanf("%d %d",&n,&m))
{
if(n==0 && m==0) break;
memset(p,0,sizeof(p));
memset(vis,0,sizeof(vis));
int x, y;
for(int i=1; i<=m; i++)
{
scanf("%d %d",&x,&y);
if(!p[x][y])
{
p[x][y] = 1;
vis[y]++;
}
}
topsort();
}
return 0;
}