MCPcopy Create free account
hub / github.com/SuprDewd/CompetitiveProgramming / HLD_naive

Class HLD_naive

code/graph/hld.test.cpp:3–76  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

1#include "../code/data-structures/union_find.cpp"
2
3struct HLD_naive {
4 int n;
5 vector<vii> adj;
6 vii parent;
7
8 HLD_naive(int _n) : n(_n), adj(n), parent(n, ii(-1, ID)) { }
9
10 void add_edge(int u, int v) {
11 adj[u].push_back(ii(v, ID));
12 adj[v].push_back(ii(u, ID));
13 parent[v] = ii(u, ID);
14 }
15
16 void update_cost(int u, int v, int c) {
17 if (parent[v].first == u)
18 swap(u, v);
19
20 assert(parent[u].first == v);
21 parent[u] = ii(v, c);
22
23 for (int i = 0; i < size(adj[u]); i++)
24 if (adj[u][i].first == v)
25 adj[u][i] = ii(v, c);
26
27 for (int i = 0; i < size(adj[v]); i++)
28 if (adj[v][i].first == u)
29 adj[v][i] = ii(u, c);
30 }
31
32 int lca(int u, int v) {
33 vi uat, vat; int res = -1;
34 while (u != -1) uat.push_back(u), u = parent[u].first;
35 while (v != -1) vat.push_back(v), v = parent[v].first;
36 u = (int)size(uat) - 1, v = (int)size(vat) - 1;
37 while (u >= 0 && v >= 0 && uat[u] == vat[v])
38 res = uat[u], u--, v--;
39 return res;
40 }
41
42 // int query_upto(int u, int v) {
43
44 // }
45
46 int query(int u, int v) {
47 // int l = lca(u, v);
48 // return f(query_upto(u, l), query_upto(v, l));
49
50 vector<bool> visited(n, false);
51 stack<ii> S;
52 S.push(ii(u, ID));
53 visited[u] = true;
54
55 while (!S.empty())
56 {
57 ii cur = S.top(); S.pop();
58 // printf("%d\n", cur.first);
59
60 if (cur.first == v)

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected