XOJ 拓扑排序

Topological sorting

Find the lexicographicalally smallest topological sorting of given directed acyclic graph G.

Input

The first line contains n,m, which denote the number of vertices and edges.

The following m lines contain ai,bi, which denote edge aibi.

(1n105^,0m10^6,1ai,bin)

Output

n integers denotes the desired sorting.

Sample input

3 2
1 3
2 3

Sample output

1 2 3

Note

Both 123 and 213 are valid topological sortings.

 

拓扑排序+优先队列,开始没用优先队列果然卡不过时间。。。

代码:

View Code
 1 #include<iostream>
 2 #include<cstring>
 3 #include<cstdio>
 4 #include<queue>
 5 #include<vector>
 6 using namespace std;
 7 #define maxn 200000
 8 priority_queue<int,vector<int>,greater<int> > q;
 9 vector<int> g[maxn];
10 int rudu[maxn],top,n,ans[maxn],num;
11 void topo()
12 {
13     for(int i=1;i<=n;i++)
14         if(!rudu[i])
15             q.push(i);
16     while(!q.empty())
17     {
18         int top=q.top();
19         ans[num++]=top;
20         q.pop();
21         for(int i=0;i<g[top].size();i++)
22         {
23             rudu[g[top][i]]--;
24             if(!rudu[g[top][i]])
25                 q.push(g[top][i]);
26         }
27     }
28 }
29 int main()
30 {
31     int m,a,b,i;
32     while(~scanf("%d %d",&n,&m))
33     {
34         memset(rudu,0,sizeof(rudu));
35         num=0;
36         while(m--)
37         {
38             scanf("%d %d",&a,&b);
39             g[a].push_back(b);
40             rudu[b]++;
41         }
42         topo();
43         for(i=0;i<num;i++)
44             if(i==num-1)
45                 printf("%d\n",ans[i]);
46             else
47                 printf("%d ",ans[i]);
48     }
49     return 0;
50 }

 

posted on 2013-02-05 20:22  acoderworld  阅读(112)  评论(0)    收藏  举报

导航