逆序最大字典序拓扑序
反向建边,逆序字典序最大。。
#include<cstdio> #include<cstring> #include<iostream> #include<algorithm> #include<cmath> #include<queue> #define N 1000005 using namespace std; priority_queue<int> q; int e=1,head[N],T,n,m,in[N],now,ans[N]; struct edge{int v,next;}ed[N]; void add(int u,int v){ ed[e].v=v; ed[e].next=head[u]; head[u]=e++; } int main(){ scanf("%d",&T); while(T--){ e=1; memset(head,0,sizeof head); memset(in,0,sizeof in); scanf("%d%d",&n,&m); int u,v; for(int i=1;i<=m;i++){ scanf("%d%d",&u,&v); in[u]++; add(v,u); } for(int i=1;i<=n;i++) if(!in[i])q.push(i); now=0; while(!q.empty()){ int x=q.top();q.pop(); ans[++now]=x; for(int i=head[x];i;i=ed[i].next){ int v=ed[i].v; in[v]--; if(!in[v])q.push(v); } } if(now==n){ for(int i=n;i>=1;i--)printf("%d ",ans[i]); printf(" "); } else printf("Impossible! "); } return 0; }