P3243-[HNOI2015]菜肴制作【拓扑排序,优先队列】
生活随笔
收集整理的這篇文章主要介紹了
P3243-[HNOI2015]菜肴制作【拓扑排序,优先队列】
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
正題
題目鏈接:https://www.luogu.com.cn/problem/P3243
題目大意
nnn個數,有mmm個要求形如xxx在yyy的前面,現在要求在i?1i-1i?1盡量靠前的情況下iii盡量靠前(i>1)(i>1)(i>1)
求這個序列
解題思路
這個很顯然要求是張有向圖無環圖,然后若第iii個數排在第xxx位,那么pi=xp_i=xpi?=x,那么就是要求ppp的字典序最小。但是發現如果直接拓撲排序+優先隊列就會導致拓撲序的字典序最小,不符合題意,但是如果我們將拓撲圖反過來跑就是正確答案了。
這樣子跑是保證了反過來的字典序最大,那么小的一定在后面也就是保證了反過來后pip_ipi?小的一定在前面。
時間復雜度O(n)O(n)O(n)
codecodecode
#include<cstdio> #include<cstring> #include<algorithm> #include<queue> using namespace std; const int N=1e5+10; struct node{int to,next; }a[N]; int T,n,m,tot,cnt,in[N],ls[N],top[N]; priority_queue<int> q; void addl(int x,int y){a[++tot].to=y;a[tot].next=ls[x];ls[x]=tot;in[y]++;return; } void topsort(){for(int i=1;i<=n;i++)if(!in[i])q.push(i);while(!q.empty()){int x=q.top();top[++cnt]=x;q.pop();for(int i=ls[x];i;i=a[i].next){int y=a[i].to;in[y]--;if(!in[y])q.push(y);}}return; } int main() {scanf("%d",&T);while(T--){tot=cnt=0;memset(ls,0,sizeof(ls));memset(in,0,sizeof(in));scanf("%d%d",&n,&m);for(int i=1;i<=m;i++){int x,y;scanf("%d%d",&x,&y);addl(y,x);}topsort();if(cnt!=n)printf("Impossible!");else{for(int i=n;i>=1;i--)printf("%d ",top[i]);}putchar('\n');}return 0; }總結
以上是生活随笔為你收集整理的P3243-[HNOI2015]菜肴制作【拓扑排序,优先队列】的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 台式电脑怎么选台式电脑怎么买
- 下一篇: P6688-可重集【字符串hash,线段