【BZOJ】[HNOI2015]菜肴制作

时间:2022-03-03 23:01:27

题目链接:http://www.lydsy.com/JudgeOnline/problem.php?id=4010


要是考场上想不出,但是还是有一个分治的做法的嘛

做法就是反向连边,然后再反向输出字典序最大的拓扑序。

 #include<iostream>
#include<cstdio>
#include<algorithm>
#include<vector>
#include<cstdlib>
#include<cmath>
#include<cstring>
#include<queue>
using namespace std;
#define maxn 1001000
#define llg long long
#define yyj(a) freopen(a".in","r",stdin),freopen(a".out","w",stdout);
llg n,m,du[maxn],bj[maxn],dl[maxn],tail,T;
vector<llg>a[maxn]; struct node
{
llg po,du;
bool operator <(const node&a)const
{
if (a.du==du) return a.po>po;
else return a.du<du;
}
}; priority_queue<node>q; void init()
{
for (llg i=;i<=n;i++) a[i].clear(),du[i]=;
cin>>n>>m;
for (llg i=;i<=m;i++)
{
llg x,y;
scanf("%lld%lld",&x,&y);
a[y].push_back(x);
du[x]++;
}
while (!q.empty()) q.pop();
for (llg i=;i<=n;i++)
{
node e;
e.po=i;
e.du=du[i];
q.push(e);
}
} bool work()
{
for (llg i=;i<=n;i++) bj[i]=;
tail=;
while (!q.empty())
{
node w=q.top();
q.pop();
if (bj[w.po]) continue;
bj[w.po]=;
if (w.du!=) return ;
dl[++tail]=w.po;
llg x=w.po;
llg W=a[x].size();
for (llg i=;i<W;i++)
{
llg v=a[x][i];
node e;
e.po=v; du[v]--; e.du=du[v];
q.push(e);
}
}
return ;
} int main()
{
yyj("a");
cin>>T;
while (T--)
{
init();
if (!work()) puts("Impossible!");
else
{
for (llg i=tail;i>=;i--) printf("%lld ",dl[i]);
printf("\n");
}
}
return ;
}