做完这个题感觉熟练掌握了PE自动机。
我还能说什么。。。
开始想错了,直接贪心+拓扑排序,结果发现第三组样例就过不了。
第三组样例是 5->2 4->3,想了想是因为5的原因而使2到了后面。。于是我就将图反过来试了一下,手画了几组好像没问题。。交上去居然A了。。瞬间不知所措。。我真的只是猜猜。。
#include<iostream>
#include<cstdio>
#include<queue>
#include<cstring>
using namespace std;
int n,m,T,cnt,ans[100005],head[100005],list[100005],next[100005],ind[100005];
priority_queue<int,vector<int> > q;
inline int read()
{
int a=0,f=1; char c=getchar();
while (c<'0'||c>'9') {if (c=='-') f=-1; c=getchar();}
while (c>='0'&&c<='9') {a=a*10+c-'0'; c=getchar();}
return a*f;
}
inline void insert(int x,int y)
{
next[++cnt]=head[x];
head[x]=cnt;
list[cnt]=y;
ind[y]++;
}
inline void toposort()
{
for (int i=1;i<=n;i++)
if (!ind[i]) q.push(i);
while (!q.empty())
{
int x=q.top(); q.pop();
ans[++ans[0]]=x;
for (int i=head[x];i;i=next[i])
{
ind[list[i]]--;
if (!ind[list[i]]) q.push(list[i]);
}
}
}
int main()
{
T=read();
for (int j=1;j<=T;j++)
{
n=read(); m=read();
memset(ind,0,sizeof(ind));
memset(head,0,sizeof(head));
cnt=0; ans[0]=0;
for (int i=1;i<=m;i++)
{
int u=read(),v=read();
insert(v,u);
}
toposort();
if (ans[0]!=n)
{
puts("Impossible!");
continue;
}
for (int i=ans[0];i;i--) printf("%d ",ans[i]);
puts("");
}
return 0;
}