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->4->2, 5->3->2,如果我們考慮正向建圖的話得出的拓撲序列爲 1 4 5 3 2。但是實際上,在圖中 1 4 與 5 3 之間並沒有約束,並且負責人在排序的時候會先去考慮 3 號的位置,於是有另一種結果 1 5 3 4 2。
代碼
#include <cstdio>
#include <cstring>
#include <vector>
#include <iostream>
#include <queue>
#include <algorithm>
using namespace std;
const int maxn =30005;
vector<int>G[maxn];
int topo[maxn];
int deg[maxn];
int m,n;
void init()
{
for(int i = 1 ; i <= m ; i ++)
G[i].clear();
memset(deg, 0, sizeof(deg));
}
void toposort()
{
priority_queue<int,vector<int>,less<int> >q;
for(int i = 1;i <= m;i ++)
if(!deg[i])
q.push(i);
int t = 1;
while(!q.empty())
{
int u = q.top();
q.pop();
topo[t++] = u;
for(int v = 0;v< G[u].size();v++)
{
deg[G[u][v]] --;
if(deg[G[u][v]] == 0)
q.push(G[u][v]);
}
}
}
int main()
{
int t, a, b;
scanf("%d", &t);
while(t--)
{
scanf("%d %d", &m, &n);
init();
for(int i = 0 ; i < n ; i ++)
{
scanf("%d %d", &a, &b);
deg[a]++; //度+1;
G[b].push_back(a);
}
toposort();
for(int i = m ; i >= 1 ; i --)
{
if(i != 1)
printf("%d ",topo[i]);
else
printf("%d\n",topo[i]);
}
}
return 0;
}