-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy patharbol.cpp
74 lines (61 loc) · 2.17 KB
/
arbol.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 <bits/stdc++.h>
using namespace std;
// Definiciones iniciales.
typedef vector<int> Lista;
// Arbol con Heavy-Light Decomposition.
// Los nodos estan indexados de 0 a n - 1.
struct HeavyLight {
int n, conteo;
Lista nivel, tamano, up;
Lista indice, super, top;
vector<Lista> aristas;
HeavyLight(int N) : n(N), conteo(),
top(N), nivel(N), tamano(N), up(N),
indice(N), super(N), aristas(N) {}
void AgregarArista(int u, int v) {
aristas[u].push_back(v);
aristas[v].push_back(u);
}
void CalcularNivel(int u, int p) {
for (int i = 0; i < aristas[u].size(); ++i) {
int v = aristas[u][i]; if (p == v) continue;
if (super[u] == super[v]) nivel[v] = nivel[u];
else nivel[v] = nivel[u] + 1;
CalcularNivel(v, u);
}
}
// Construir realiza todas las operaciones para
// trabajar con Heavy-Light. Por defecto, la raiz del
// arbol se establece como el nodo 0. Si quieren definir
// una raiz diferente, llamen Construir(r) donde el
// parametro r indica cual sera la raiz del arbol.
int Construir(int u = 0, int p = -1) {
int tam_subarbol = 0;
up[u] = p, super[u] = -1;
for (int i = 0; i < aristas[u].size(); ++i) {
int v = aristas[u][i]; if (p == v) continue;
tam_subarbol += Construir(v, u);
}
for (int i = 0; i < aristas[u].size(); ++i) {
int v = aristas[u][i]; if (p == v) continue;
if (tamano[v] > tam_subarbol / 2)
indice[u] = indice[v] + 1,
super[u] = super[v],
top[super[v]] = u;
}
if (super[u] == -1) super[u] = conteo,
top[conteo++] = u;
if (p == -1) CalcularNivel(u, p);
return tamano[u] = tam_subarbol + 1;
}
int LCA(int u, int v) {
if (nivel[v] > nivel[u]) swap(u, v);
while (nivel[u] > nivel[v]) u = up[top[super[u]]];
while (super[u] != super[v]) u = up[top[super[u]]],
v = up[top[super[v]]];
return (indice[u] > indice[v])? u: v;
}
};
int main() {
return 0;
}