题目

Solution

讲课的PPT里的图

Code

#include<bits/stdc++.h>
using namespace std;
const int N=100002;
struct node{
	int to,ne;
}e[N];
int T,i,d[N],x,y,ans[N],n,m,tot,h[N],cnt;
priority_queue<int>q;
inline char gc(){
	static char buf[100000],*p1=buf,*p2=buf;
	return p1==p2&&(p2=(p1=buf)+fread(buf,1,100000,stdin),p1==p2)?EOF:*p1++;
}
inline int rd(){
	int x=0,fl=1;char ch=gc();
	for (;ch<48||ch>57;ch=gc())if(ch=='-')fl=-1;
	for (;48<=ch&&ch<=57;ch=gc())x=(x<<3)+(x<<1)+(ch^48);
	return x*fl;
}
inline void wri(int a){if(a<0)a=-a,putchar('-');if(a>=10)wri(a/10);putchar(a%10|48);}
inline void wln(int a){wri(a);puts("");}
void add(int x,int y){e[++tot]=(node){y,h[x]},h[x]=tot;}
int main(){
	for (T=rd();T--;){
		n=rd(),m=rd();
		tot=0,memset(h,0,n+1<<2),memset(d,0,n+1<<2);
		for (i=1;i<=m;i++) x=rd(),y=rd(),add(y,x),d[x]++;
		for (i=1;i<=n;i++)
			if (!d[i]) q.push(i);
		cnt=0;
		while (!q.empty()){
			x=q.top(),q.pop();
			ans[cnt++]=x;
			for (i=h[x];i;i=e[i].ne){
				d[y=e[i].to]--;
				if (!d[y]) q.push(y);
			}
		}
		if (cnt<n) puts("Impossible!");
		else{
			for (i=n-1;i;i--) wri(ans[i]),putchar(' ');
			wln(ans[0]);
		}
	}
}