反向考虑 这样才能解决"穷人在后"的问题
反例:
6 1
6 1
#include <bits/stdc++.h>
using namespace std;
struct node1
{
int v;
int next;
};
struct node2
{
bool friend operator < (node2 n1,node2 n2)
{
return n1.id<n2.id;
}
int id;
};
node1 edge[100010];
priority_queue <node2> que;
int first[30010],degree[30010],ans[30010];
int n,m,num;
void addedge(int u,int v)
{
edge[num].v=v;
edge[num].next=first[u];
first[u]=num++;
return;
}
int main()
{
node2 cur,tem;
int t,i,u,v;
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&n,&m);
memset(first,-1,sizeof(first));
memset(degree,0,sizeof(degree));
num=0;
for(i=1;i<=m;i++)
{
scanf("%d%d",&u,&v);
addedge(v,u);
degree[u]++;
}
while(!que.empty()) que.pop();
num=0;
for(i=1;i<=n;i++)
{
if(!degree[i])
{
tem.id=i;
que.push(tem);
}
}
while(!que.empty())
{
cur=que.top();
que.pop();
u=cur.id;
ans[++num]=u;
for(i=first[u];i!=-1;i=edge[i].next)
{
v=edge[i].v;
degree[v]--;
if(!degree[v])
{
tem.id=v;
que.push(tem);
}
}
}
for(i=num;i>=2;i--)
{
printf("%d ",ans[i]);
}
printf("%d\n",ans[i]);
}
return 0;
}