poj2367 Genealogical tree

Posted 王宜鸣

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了poj2367 Genealogical tree相关的知识,希望对你有一定的参考价值。

思路:

拓扑排序,这里是用染色的dfs实现的。在有环的情况下可以判断出来,没有环的情况下输出拓扑排序序列。

实现:

 1 #include <vector>
 2 #include <cstring>
 3 #include <iostream>
 4 #include <algorithm>
 5 #define w 0
 6 #define g 1
 7 #define b 2
 8 using namespace std;
 9 const int N = 105;
10 int G[N][N];
11 vector<int> res, vis;
12 bool cycle;
13 int n, m;
14 void init()
15 {
16     cycle = false;
17     cin >> n;
18     memset(G, 0, sizeof G);
19     for (int i = 0; i <= n; i++) vis.push_back(w);
20     int x;
21     for (int i = 1; i <= n; i++)
22     {
23         while (cin >> x, x)
24         {
25             G[i][x] = 1;
26         }
27     }
28 }
29 void dfs(int u)
30 {
31     if (vis[u] == b) return;
32     if (vis[u] == g) { cycle = true; return; }
33     vis[u] = g;
34     for (int i = n; i >= 1; i--)
35     {
36         if (G[u][i]) dfs(i);
37     }
38     vis[u] = b;
39     res.push_back(u);
40     return;
41 }
42 void topsort()
43 {
44     for (int i = n; i >= 1; i--)
45     {
46         if (vis[i] == w) dfs(i);
47     }
48     reverse(res.begin(), res.end());
49 }
50 int main()
51 {
52     init();
53     topsort();
54     if (cycle) cout << "There is a cycle in G!" << endl;
55     else
56     {
57         for (int i = 0; i < res.size(); i++)
58             cout << res[i] << " ";
59         cout << endl;
60     }
61     return 0;
62 }

 

以上是关于poj2367 Genealogical tree的主要内容,如果未能解决你的问题,请参考以下文章

POJ 2367 Genealogical tree 拓扑排序入门题

poj2367 Genealogical tree

图论之拓扑排序 poj 2367 Genealogical tree

拓扑排序 POJ2367Genealogical tree[topo-sort]

(拓扑排序)POJ - 2367 Genealogical tree

POJ 2367 Genealogical tree 拓扑题解