1 2 4 3
很直白的拓扑排序
#include<cstdio>
#include<cstdlib>
#include<cstring>
using namespace std;
int map[1001][1001];
int die[1001];
int cun[1001];
void topo(int n)
{
int i,j,first,cut=0;
for(i=0;i<n;i++)
{
for(j=1;j<=n;j++)
{
if(die[j]==0)
{
first=j;
break;
}
}
cun[cut++]=first; die[first]=-1;
for(j=1;j<=n;j++)
{
if(map[first][j]==1)
{
die[j]--;
}
}
}
printf("%d",cun[0]);
for(i=1;i<n;i++)
{
printf(" %d",cun[i]);
}
printf("\n");
}
int main()
{
int n,m;
while(scanf("%d%d",&n,&m)!=EOF)
{
memset(map,0,sizeof(map));
memset(die,0,sizeof(die));
int x,y;
while(m--)
{
scanf("%d%d",&x,&y);
if(map[x][y]==0)
{
map[x][y]=1;
die[y]++;
}
}
topo(n);
}
return 0;
}