HDU 4857 逃生 (優先隊列+反向拓撲)

來源:互聯網
上載者:User

標籤:style   blog   http   color   os   io   

題目連結:http://acm.hdu.edu.cn/showproblem.php?pid=4857

解題報告:有n個點,有m個條件限制,限制是像這樣的,輸入a  b,表示a必須排在b的前面,如果不能確定兩個數誰排在前面則盡量把小的排在前面。

首先把出度為0的點加入到優先隊列中,然後每次用優先隊列中彈出的點去更新其它點的出度,更新的同時如果又有其它點的出度為0的話又加到優先隊列中,

最後按照從優先隊列中出隊的反序輸出就可以了。我還是不懂為什麼按照入度為0然後加入到優先隊列然後正序輸出這樣為什麼不行。希望有懂的人可以告訴我。

 1 #include<cstdio> 2 #include<cstring> 3 #include<iostream> 4 #include<algorithm> 5 #include<queue> 6 #include<vector> 7 using namespace std; 8 const int maxn = 30000+5; 9 10 priority_queue<int> que;11 vector<int> vt[maxn];12 int du[maxn],ans[maxn];13 int main()14 {15     int T,n,m;16     scanf("%d",&T);17     while(T--)18     {19         scanf("%d%d",&n,&m);20         int u,v;21         for(int i = 1;i <= n;++i)22         vt[i].clear();23         memset(du,0,sizeof(du));24         while(m--)25         {26             scanf("%d%d",&u,&v);27             du[u]++;28             vt[v].push_back(u);29         }30         for(int i = 1;i <= n;++i) //把出度為0的先加到優先隊列中31         if(!du[i]) que.push(i);32         int f = n - 1;33         while(!que.empty())34         {35             int s = que.top();36             que.pop();37             ans[f--] = s;38             int len = vt[s].size();39             for(int i = 0;i < len;++i)40             {41                 int tt = vt[s][i];42                 du[tt]--;43                 if(du[tt] == 0) que.push(tt);44             }45         }46         for(int i = 0;i < n;++i)47         printf(i == 0? "%d":" %d",ans[i]);48         puts("");49     }50     return 0;51 }
View Code

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.