糟糕的事情发生啦,现在大家都忙着逃命。但是逃命的通道很窄,大家只能排成一行。
现在有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
看上去就是普通的拓扑排序
其实就是普通的拓扑排序
只是就算不在图里的也要加进去。。。
而且这个向外吐的时候要从大到小吐
因为还有个数字越小越向前的优先级。。
#include <iostream>
#include <cstring>
#include<algorithm>
#include <cstdio>
#include<vector>
#include<queue>
#include<string>
#include<map>
#include<stack>
using namespace std;
vector<int>tu[300001];
int rudu[30001];
map<int, int>mp;
int n, m;
int main()
{
int T;
cin >> T;
while (T--)
{
mp.clear();
cin >> n >> m;
for (int a = 1; a <= n; a++)tu[a].clear();
int q, w;
for (int a = 1; a <= m; a++)
{
scanf("%d%d", &q, &w);
tu[w].push_back(q);
rudu[q]++;
}
priority_queue<int>qq;
for (int a = 1; a <= n; a++)
{
if (rudu[a])continue;
qq.push(a);
}
stack<int>st;
while (!qq.empty())
{
st.push(qq.top());
qq.pop();
for (int a = 0; a < tu[st.top()].size(); a++)
{
rudu[tu[st.top()][a]]--;
if (rudu[tu[st.top()][a]])continue;
int er = tu[st.top()][a];
qq.push(er);
}
}
int jc = 0;
while (!st.empty())
{
if (!jc)
{
jc = 1;
printf("%d", st.top());
st.pop();
continue;
}
printf(" %d", st.top());
st.pop();
}
printf("\n");
}
}