题目链接:hdu1285
拓扑排序,但题目要求按序号排出,按普通的拓扑排序不行,所以就每次从前往后搜
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
int map[505][505];
int ans[505],du[505];
int n,i,j;
void toposort()
{
for(i = 1 ; i <= n ; i ++)
for(j = 1 ; j <= n ; j ++)
if(map[i][j])
du[j] ++;//入度加1
int num = 1;
while(num <= n)
{
i = 1;
while(du[i]) i++;//找到入度为0的点
ans[num++] = i;
du[i] = -1;
for(j = 1 ; j <= n ; j ++)
if(map[i][j])
du[j]--;//将所有与节点i相连的节点的入度值全部减1
}
}
int main()
{
int m;
while(~scanf("%d%d",&n,&m))
{
memset(map,0,sizeof(map));
memset(du,0,sizeof(du));
while(m--)
{
scanf("%d%d",&i,&j);
map[i][j] = 1;
}
toposort();
for(i = 1 ; i < n; i ++)
printf("%d ",ans[i]);
printf("%d\n",ans[n]);
}
return 0;
}