逃生
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 4295 Accepted Submission(s): 1207
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
Author
CLJ
Source
BestCoder Round #1
——————————————————————————————————————————————
其实一开始不明白为什么要反向构图,倒叙输出。
后来仔细看了一下题目。
————————
input:
1
3 1
3 1
answer:
3 1 2
——————
input:
2
5 3
5 2
3 1
3 4
4 2
4 1
3 2
answer:
3 1 5 2 4
4 1 3 2
————————
在HD 上有一组测试数据很典型,如上。
题目要求在没有约束条件(直接或间接)的情况下,编号小的排在前面。
所以实际情况是:编号小的连带着它的约束排在前面,编号大的连带着它的约束排在后面。
拿第一组数据举例,本来应该是 3 1 2,因为 3 - > 1有入度,如果正向构图的话,每次取最小且入度为0的,那么输出就会是 2 1 3,因为 2 的入度为0。
所以用,优先队列配合反向构图存储。
——————————————————————————————————————————————
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
using namespace std;
const int MAX_N = 100000+5;
int ans[30010];
int indegree[30010];
int head[MAX_N];
int num;
struct EDGE{
int to,next;
}edge[MAX_N];
void init()
{
memset(head,-1,sizeof(head));
memset(indegree,0,sizeof(indegree));
}
//void add( int a,int b )
//{
// edge[num].next = head[b];
// edge[num].to = a;
// head[b] = num++;
// indegree[a]++;
//}
void toposort( int n )
{
int k = 0;
priority_queue<int>que;
//while( que.size() ) que.pop();
for( int i=1; i<=n; i++ )
{
if( indegree[i] == 0 )
que.push(i);
}
while( que.size() )
{
int u = que.top();
que.pop();
ans[k++] = u;
for( int i=head[u] ; i!=-1; i=edge[i].next )
{
int v = edge[i].to;
indegree[v]--;
if( indegree[v] == 0 )
que.push(v);
}
}
for( int i=k-1; i>=0; i-- )
{
if( i != 0 )printf("%d ",ans[i]);
else printf("%d\n",ans[0]);
}
}
int main()
{
int t,m,n,a,b;
scanf("%d",&t);
while( t-- )
{
scanf("%d%d",&n,&m);
init();
for( int i=0; i<m; i++ )
{
scanf("%d%d",&a,&b);
edge[i].next = head[b];
edge[i].to = a;
head[b] = i;
indegree[a]++;
}
toposort(n);
}
return 0;
}