HDU4857逃生(拓扑排序)

Description

Input

Output

Sample Input
1
5 10
3 5
1 4
2 5
1 2
3 4
1 4
2 3
1 5
3 5
1 2
Sample Output

1 2 3 4 5

#include<stdio.h>
#include<queue>
#include<vector>
#include<cstring>
#include<cstdlib>
#include<algorithm>
using namespace std;
#define MAX 100005
priority_queue<int,vector<int>,less<int > >q;//此处应该为从大到小
vector<int> map[MAX];
int indegree[MAX];
int que[MAX];//存储
void topsort(int n)
{
int i;
for(i=1;i<=n;i++)
if(indegree[i]==0)
q.push(i);
int j=0;
memset(que,0,sizeof(que));
while(!q.empty())
{
int v=q.top();
q.pop();
que[j++]=v;
for(int k=0;k<map[v].size();k++)
{
indegree[map[v][k]]--;
if(indegree[map[v][k]]==0)
q.push(map[v][k]);
}
}
for(i=j-1;i>0;i--)
printf("%d ",que[i]);
printf("%d\n",que[0]);
}
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
int n,m;
scanf("%d%d",&n,&m);
memset(indegree,0,sizeof(indegree));
for(int i=1;i<=n;i++)
map[i].clear();
while(m--)
{
int a,b;
scanf("%d%d",&a,&b);
map[b].push_back(a);//将a放在b的后边，建立反向边的关系
indegree[a]++;
}
topsort(n);
}
return 0;
}