-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathfu.cpp
93 lines (83 loc) · 1.58 KB
/
fu.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#include <vector>
#include <cstdlib>
#include "fu.h"
using namespace std;
template<typename T>
struct fu
{
T label;
find_union<T> up;
int rank, size;
vector<find_union<T>> elems;
};
template<typename T>
find_union<T> create_fu(T label)
{
find_union<T> res = (find_union<T>)malloc(sizeof(fu<T>));
res->label = label;
res->up = NULL;
res->rank = 0;
res->size = 1;
res->elems= {};
return res;
}
template<typename T>
find_union<T> go_up(find_union<T> p)
{
if (p->up == NULL)
return p;
return (p->up = go_up(p->up));
}
template<typename T>
int find(find_union<T> p)
{
return go_up(p)->label;
}
template<typename T>
bool equivalent(find_union<T> p, find_union<T> q)
{
return go_up(p) == go_up(q);
}
template<typename T>
void union_fu(find_union<T> p, find_union<T> q)
{
find_union<T> rp = go_up(p);
find_union<T> rq = go_up(q);
if (rp == rq)
return;
if (rp->rank > rq->rank)
{
rq->up = rp;
rp->size += rq->size;
rp->elems.push_back(rq);
}
else
{
rp->up = rq;
rq->size += rp->size;
rq->elems.push_back(rp);
if (rq->rank == rp->rank)
rq->rank++;
}
}
template<typename T>
int size(find_union<T> p)
{
return go_up(p)->size;
}
template<typename T>
void _traverse(find_union<T> p, vector<int> &res)
{
res.push_back(p->label);
for (find_union<T> q : p->elems)
{
_traverse(q, res);
}
}
template<typename T>
vector<int> elements(find_union<T> p)
{
vector<int> res;
_traverse(go_up(p), res);
return res;
}