BZOJ 4010 HNOI2015 菜肴製作 拓撲排序+堆,bzojhnoi2015

來源:互聯網
上載者:User

BZOJ 4010 HNOI2015 菜肴製作 拓撲排序+堆,bzojhnoi2015

題目大意:給定一張無向圖,求一個拓撲序,使:
1的位置最靠前
在保證上面的條件下使2的位置最靠前
在保證上面的條件下使3的位置最靠前
……
注意不是字典序最小!例如範例3

建立反圖,對反圖求字典序最大的拓撲序,然後反向輸出即可。
我不知道為什麼。真的不知道。
求個解答線上等。

#include <cstdio>#include <cstring>#include <iostream>#include <algorithm>#define M 100100using namespace std;struct abcd{    int to,next;}table[M];int head[M],tot;int n,m;int degree[M];int stack[M],top;void Add(int x,int y){    table[++tot].to=y;    table[tot].next=head[x];    head[x]=tot;}void Initialize(){    memset(head,0,sizeof head);    tot=1;    memset(degree,0,sizeof degree);}namespace Priority_Queue{    int heap[M],top;    void Insert(int x)    {        heap[++top]=x;        int t=top;        while(t>1)        {            if(heap[t]>heap[t>>1])                swap(heap[t],heap[t>>1]),t>>=1;            else                break;        }    }    void Pop()    {        heap[1]=heap[top--];        int t=2;        while(t<=top)        {            if( t<top && heap[t+1]>heap[t] )                ++t;            if(heap[t]>heap[t>>1])                swap(heap[t],heap[t>>1]),t<<=1;            else                break;        }    }}void Topology_Sort(){    using namespace Priority_Queue;    int i;    for(i=1;i<=n;i++)        if(!degree[i])            Insert(i);    while(Priority_Queue::top)    {        int x=heap[1];Pop();        stack[++::top]=x;        for(i=head[x];i;i=table[i].next)            if(!--degree[table[i].to])                Insert(table[i].to);    }}int main(){    int T,i,x,y;    for(cin>>T;T;T--)    {        Initialize();        scanf("%d%d",&n,&m);        for(i=1;i<=m;i++)        {            scanf("%d%d",&x,&y);            Add(y,x);            degree[x]++;        }        top=0;        Topology_Sort();        if(top!=n)            puts("Impossible!");        else        {            for(i=n;i;i--)                printf("%d ",stack[i],i==1?'\n':' ');            puts("");        }    }    return 0;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.