拓扑排序示例程序

输入:顶点个数n,边数m,然后是m行,表示每条边的起点和终点u, v 表示从顶点u到顶点v的一条有向边。输入0 0 表示结束。

输出:如果不存在有向环,则输出一个拓扑有序序列;否则,输出“Netword has a cycle!”

 

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstdlib>
 4 #include <cstring>
 5 #include <cctype>
 6 #include <stack>
 7 #include <queue>
 8 #include <map>
 9 #include <set>
10 #include <vector>
11 #include <cmath>
12 #include <algorithm>
13 #define lson l, m, rt<<1
14 #define rson m+1, r, rt<<1|1
15 using namespace std;
16 typedef long long int LL;
17 const int MAXN =  0x3f3f3f3f;
18 const int  MIN =  -0x3f3f3f3f;
19 const double eps = 1e-9;
20 const int dir[8][2] = {{0,1},{1,0},{0,-1},{-1,0},{-1,1},
21   {1,1},{1,-1},{-1,-1}};
22 int n, m, Count[100], i, j, top, out[100];
23 struct ArcNode{
24   int to; struct ArcNode *next;
25 };
26 ArcNode *List[100];
27 void topsort()
28 {
29   ArcNode *temp; top = -1; int k, len = 0; bool flag = true;
30   for (i = 0; i < n; ++i) {
31     if (Count[i] == 0) {
32       Count[i] = top; top = i;
33     }
34   }
35   for (i = 0; i < n; ++i) {
36     k = top; if (k == -1) { flag = false; break; }
37     top = Count[k]; temp = List[k]; out[len++] = k + 1;
38     while (temp != NULL) {
39       Count[temp->to]--;
40       if (Count[temp->to] == 0) {
41         Count[temp->to] = top; top = temp->to;
42       } temp = temp->next;
43     }
44   }
45   if (flag) {
46     for (i = 0; i < len; ++i) {
47       if (!i) printf("%d", out[i]); else printf(" %d", out[i]);
48     } printf("\n");
49   } else printf("Network has a cycle!\n");
50   for (i = 0; i < n; ++i) {
51     temp = List[i];
52     while (temp) {
53       List[i] = temp->next; delete temp; temp = List[i];
54     }
55   }
56 }
57 int main(void){
58 #ifndef ONLINE_JUDGE
59   freopen("topsort.in", "r", stdin);
60 #endif
61   while (~scanf("%d%d", &n, &m)){
62     if (m + n == 0) break;
63     int u, v; ArcNode *temp;
64     memset(Count, 0, sizeof(Count));
65     memset(List, 0, sizeof(List));
66     memset(out, 0, sizeof(out));
67     for (i = 0; i < m; ++i){
68       scanf("%d%d", &u, &v); u--; v--;
69       temp = new ArcNode; temp->next = NULL; temp->to = v;
70       temp->next = List[u]; List[u] = temp; Count[v]++;
71     }
72     topsort();
73   }
74 
75   return 0;
76 }

 

 

 

用数组实现的链式栈 ,好神奇……

posted on 2013-04-28 01:51  aries__liu  阅读(294)  评论(0编辑  收藏  举报