1. 程式人生 > >HDU 4857 逃生(拓撲排序逆向+鄰接表存圖)

HDU 4857 逃生(拓撲排序逆向+鄰接表存圖)

panel scrip topo %d tar ons back int queue

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

題目:

Problem Description 糟糕的事情發生啦,現在大家都忙著逃命。但是逃命的通道很窄,大家只能排成一行。

現在有n個人,從1標號到n。同時有一些奇怪的約束條件,每個都形如:a必須在b之前。
同時,社會是不平等的,這些人有的窮有的富。1號最富,2號第二富,以此類推。有錢人就賄賂負責人,所以他們有一些好處。

負責人現在可以安排大家排隊的順序,由於收了好處,所以他要讓1號盡量靠前,如果此時還有多種情況,就再讓2號盡量靠前,如果還有多種情況,就讓3號盡量靠前,以此類推。

那麽你就要安排大家的順序。我們保證一定有解。 Input 第一行一個整數T(1 <= T <= 5),表示測試數據的個數。
然後對於每個測試數據,第一行有兩個整數n(1 <= n <= 30000)和m(1 <= m <= 100000),分別表示人數和約束的個數。

然後m行,每行兩個整數a和b,表示有一個約束a號必須在b號之前。a和b必然不同。 Output 對每個測試數據,輸出一行排隊的順序,用空格隔開。 Sample Input 1 5 10 3 5 1 4 2 5 1 2 3 4 1 4 2 3 1 5 3 5 1 2 Sample Output 1 2 3 4 5 題解:這道題目和上篇博客一樣都要逆向建圖。用鄰接表存圖,跑下優先隊列的那種拓撲排序即可。
 1
#include <stack> 2 #include <queue> 3 #include <vector> 4 #include <cstdio> 5 #include <cstring> 6 using namespace std; 7 8 const int N=30000+10; 9 int n,m; 10 int in[N]; 11 stack <int> ans; 12 vector <int> E[N]; 13 priority_queue <int> Q;
14 15 void toposort(){ 16 for(int i=1;i<=n;i++) if(!in[i]) Q.push(i); 17 while(!Q.empty()){ 18 int u=Q.top();Q.pop(); 19 ans.push(u); 20 for(int j=0;j<E[u].size();j++){ 21 int v=E[u][j]; 22 in[v]--; 23 if(in[v]==0) Q.push(v); 24 } 25 } 26 } 27 28 void init(){ 29 for(int i=0;i<N;i++) E[i].clear(); 30 memset(in,0,sizeof(in)); 31 } 32 33 int main(){ 34 int t; 35 scanf("%d",&t); 36 while(t--){ 37 int a,b; 38 init(); 39 scanf("%d%d",&n,&m); 40 for(int i=1;i<=m;i++){ 41 scanf("%d%d",&a,&b); 42 in[a]++; 43 E[b].push_back(a); 44 } 45 toposort(); 46 while(!ans.empty()){ 47 if(ans.size()==1) printf("%d\n",ans.top()); 48 else printf("%d ",ans.top()); 49 ans.pop(); 50 } 51 } 52 return 0; 53 }

HDU 4857 逃生(拓撲排序逆向+鄰接表存圖)