You’ve got N dishes and M rules about their orders. Each rule seems like <i,j>, it means you must do i first before doing j.
You perfer dish 1 first, then dish 2,3, and so on. Please find an order to do all these dishes, so that you can have dish 1 as quickly as possible. If 2 plans’ 1’s order is the same, than you perfer which can have 2 as quickly as possble (And so on).
Solution
There’s a tips that if you output the lexicographic-ordered plan, you’ll get a WA. The correct solution is to create the inverse graph, and output upside down.
#include<cstdio>#include<cstdlib>#include<cstring>#include<queue>usingnamespace std;#define reg registerstruct node{int x,y,next;}e[100010];int len=0;int T;int n,m,cnt;int sx,sy;int first[100010];int out[100010];
priority_queue<int> q;int ans[100010];voidins(int x,int y){
e[++len].x=x;e[len].y=y;++out[y];
e[len].next=first[x];first[x]=len;}voidToposort(){while(!q.empty()) q.pop();for(reg int i=1;i<=n;++i)if(!out[i])
q.push(i);while(!q.empty()){int x=q.top();q.pop();
ans[cnt--]=x;for(reg int i=first[x];i;i=e[i].next){int y=e[i].y;--out[y];if(!out[y])
q.push(y);}}}intmain(){scanf("%d",&T);while(T--){memset(first,0,sizeof(first));len=0;memset(out,0,sizeof(out));scanf("%d%d",&n,&m);for(reg int i=1;i<=m;++i){scanf("%d%d",&sx,&sy);ins(sy,sx);}
cnt=n;Toposort();if(!cnt){for(reg int i=1;i<=n;++i)printf("%d ",ans[i]);puts("");}elseprintf("Impossible!\n");}}