hdu oj 4857 逃生(反向拓扑)

题目地址http://acm.hdu.edu.cn/showproblem.php?pid=4857
逃生
Time Limit:1000MS     Memory Limit:32768KB     64bit IO Format:%I64d & %I64u
 

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


AC代码:
 1 #include<cstdio>
 2 #include<queue>
 3 #include<string.h>
 4 using namespace std;
 5 const int M = 300020;
 6 int n,m,a,b,indegree[M],qu[M],head[M];
 7 struct stu
 8 {
 9     int to, next;
10 }st[M];
11 void topo()
12 {
13     priority_queue<int>que; // 标准库默认使用元素类型的<操作符来确定它们之间的优先级关系
14    //例如依次输入5,3,2,4,6输出结果为6,5,4,3,2 
15     int i,j,k=0,s=1,m;
16     for(i = 1 ; i <= n ; i++)//找出无前驱的数存入队列 
17         if(indegree[i] == 0)
18             que.push(i);
19     while(!que.empty())
20     {
21         qu[s++] = m = que.top();//优先队列先输出大的数 
22         que.pop();//删除队列的首元素 
23         for(i = head[m] ; i != -1 ; i = st[i].next)
24         {
25             indegree[st[i].to]--;
26             if(indegree[st[i].to] == 0)
27                 que.push(st[i].to);
28         }
29     }
30     for(i = n ; i >= 1 ; i--)
31     //将队列值存入集合时先存入大的数,输入时又将a,b关系反置,所以反着输出 
32     {
33         printf("%d", qu[i]);
34         if(i == 1)    printf("\n");
35         else    printf(" ");
36     }
37 }
38 int main()
39 {
40     int t,i,j;
41     scanf("%d",&t);
42     while(t--)
43     {
44         scanf("%d %d",&n,&m);
45         memset(indegree,0,sizeof(indegree));
46         memset(head,-1,sizeof(head));
47         for(i = 0 ; i < m ; i++)
48         {
49             scanf("%d %d",&a,&b);
50             st[i].to=a;//反着记录令b在a前面(因为最后反着输出) 
51             st[i].next=head[b];
52             head[b]=i;
53             indegree[a]++;
54         }
55         topo();
56     }
57 }

 

 
 
posted @ 2016-08-05 18:04  唐唐123  阅读(201)  评论(0编辑  收藏  举报