题目链接: http://acm.hdu.edu.cn/showproblem.php?pid=1285
题目大意:
给定一个有向无环图,要求得到该图的拓扑序列(我是看过拓扑排序的资料后才知道),如果有多个序列,点标号小的点在前面;
题目分析:
直接拓扑排序即可,但是由于要考虑点标号小的在前面所以使用优先队列来写;
代码:

1 /*2012-04-25 18:07:36 Accepted 1285 15MS 332K 1316 B C++*/ 2 #include <cstdio> 3 #include <cstring> 4 #include <cmath> 5 #include <iostream> 6 #include <algorithm> 7 #include <vector> 8 #include <queue> 9 using namespace std; 10 11 #define mpair make_pair 12 #define pii pair<int,int> 13 #define MM(a,b) memset(a,b,sizeof(a)); 14 typedef long long lld; 15 typedef unsigned long long u64; 16 template<class T> bool up_max(T& a,const T& b){return b>a? a=b,1 : 0;} 17 template<class T> bool up_min(T& a,const T& b){return b<a? a=b,1 : 0;} 18 #define maxn 510 19 20 int n,m; 21 vector<int> adj[maxn]; 22 23 int in[maxn]; 24 priority_queue< int, vector<int>, greater<int> > Q; 25 void Topsort(){ 26 while( !Q.empty() ) Q.pop(); 27 for(int i=1;i<=n;++i) if( !in[i] ) Q.push(i); 28 while( !Q.empty() ){ 29 int u= Q.top(); 30 printf("%d", u); 31 Q.pop(); 32 for(int i=0;i<adj[u].size();++i){ 33 int v= adj[u][i]; 34 if( --in[v] == 0 ) 35 Q.push( v ); 36 } 37 if( Q.empty() ) puts(""); 38 else printf(" "); 39 } 40 } 41 42 int main() 43 { 44 while( cin>>n>>m ){ 45 for(int i=1;i<=n;++i) adj[i].clear(), in[i]= 0; 46 for(int i=1;i<=m;++i){ 47 int u,v; 48 scanf("%d%d", &u, &v ); 49 in[v]++; 50 adj[u].push_back( v ); 51 } 52 Topsort(); 53 } 54 }