-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLab09_TreeSet.cpp
74 lines (66 loc) · 1.24 KB
/
Lab09_TreeSet.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#include <iostream>
using namespace std;
class Node
{
public:
int father;
int root;
Node()
{
father = 0;
root = 0;
}
Node(int elememt, int fa, int ro)
{
father = fa;
root = ro;
}
};
int findRoot(int n, Node *set)
{
int root = n;
while (n != set[n].father)
{
root = set[n].father;
}
return root;
}
bool unionSet(int father, int child, Node *set)
{
if (set[father].root != set[child].root)
{
set[child].father = father;
set[child].root = set[father].root;
}
return true;
}
int main()
{
Node *set;
int nodeNum, edgeNum;
cin >> nodeNum >> edgeNum;
/*******init set*******/
set = new Node[nodeNum + 1];
for (int i = 0; i <= nodeNum; i++)
{
set[i].father = i;
set[i].root = findRoot(i, set);
}
/*******union set*******/
for (int i = 1; i <= edgeNum; i++)
{
int fa, child;
cin >> fa >> child;
unionSet(fa, child, set);
}
/*******print result*******/
int root = 0;
for (int i = 1; i <= nodeNum; i++)
{
if (set[i].root != root)
cout << '\n';
cout << i << ' ';
root = set[i].root;
}
system("pause");
}