简单的拓扑排序,要求字典序最小的话用优先队列来维护入度为0的点即可。
1 #include <iostream> 2 #include <cstring> 3 #include <cstdio> 4 #include <queue> 5 using namespace std; 6 7 const int N = 501; 8 const int M = 10000; 9 int head[N]; 10 int ans[N]; 11 int in[N]; 12 int n, m, e; 13 14 struct Edge 15 { 16 int v, next; 17 } edge[M]; 18 19 void addEdge( int u, int v ) 20 { 21 edge[e].v = v; 22 edge[e].next = head[u]; 23 head[u] = e++; 24 } 25 26 void topo() 27 { 28 priority_queue<int, vector<int>, greater<int> > q; 29 for ( int i = 1; i <= n; i++ ) 30 { 31 if ( !in[i] ) q.push(i); 32 } 33 int cnt = 0; 34 while ( !q.empty() ) 35 { 36 int u = q.top(); 37 q.pop(); 38 printf("%d", u); 39 cnt++; 40 if ( cnt != n ) putchar(' '); 41 else putchar(' '); 42 for ( int i = head[u]; i != -1; i = edge[i].next ) 43 { 44 int v = edge[i].v; 45 in[v]--; 46 if ( in[v] == 0 ) 47 { 48 q.push(v); 49 } 50 } 51 } 52 } 53 54 int main () 55 { 56 while ( scanf("%d%d", &n, &m) != EOF ) 57 { 58 e = 0; 59 memset( head, -1, sizeof(head) ); 60 memset( in, 0, sizeof(in) ); 61 while ( m-- ) 62 { 63 int u, v; 64 scanf("%d%d", &u, &v); 65 addEdge( u, v ); 66 in[v]++; 67 } 68 topo(); 69 } 70 return 0; 71 }