Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathhld.cpp
More file actions
Latest commit
133 lines (122 loc) · 2.87 KB
/
Copy pathhld.cpp
File metadata and controls
133 lines (122 loc) · 2.87 KB
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
#include<bits/stdc++.h>
usingnamespacestd;
// Timus 1553 "Caves and Tunnels"
// this implementation is actually bad
// google adamant's blogs how to code it
structsegtree {
int lb, rb;
int mx = 0;
segtree *l, *r;
segtree (int _lb, int _rb) {
lb = _lb, rb = _rb;
if (lb != rb) {
int t = (lb + rb) / 2;
l = newsegtree(lb, t);
r = newsegtree(t+1, rb);
}
}
voidupd (int k, int x) {
if (lb == rb) mx += x;
else {
int t = (lb + rb) / 2;
if (k <= t) l->upd(k, x);
else r->upd(k, x);
mx = max(l->mx, r->mx);
}
}
intget_mx (int lq, int rq) {
if (lb >= lq && rb <= rq) return mx;
elseif (lb > rq || rb < lq) return0;
returnmax(l->get_mx(lq, rq), r->get_mx(lq, rq));
}
};
constint maxn = 1e5;
int p[maxn], head[maxn], d[maxn], s[maxn];
int tin[maxn], tout[maxn];
segtree* tree[maxn];
vector<int> g[maxn];
int timer = 0;
voiddfs1 (int v) {
tin[v] = timer++;
s[v] = 1;
for (int u : g[v]) {
if (u != p[v]) {
d[u] = d[v]+1;
p[u] = v;
dfs1(u);
s[v] += s[u];
}
}
tout[v] = timer++;
}
voiddfs2 (int v) {
if (g[v].empty() || (g[v].size() == 1 && p[v] != -1))
tree[v] = newsegtree(0, d[v] - d[head[v]]);
else{
int mx = -1;
for (int u : g[v])
if (u != p[v] && (mx == -1 || s[u] > s[mx]))
mx = u;
for (int u : g[v])
if (u != p[v] && u != mx)
head[u] = u, dfs2(u);
head[mx] = head[v];
dfs2(mx);
tree[v] = tree[mx];
}
}
intdist (int v) {
return d[v]-d[head[v]];
}
boolancestor (int v, int u) {
return tin[v] <= tin[u] && tin[u] <= tout[v];
}
intquery (int v, int u) {
int ans = 0;
while (!ancestor(head[v], u)) {
ans = max(ans, tree[v]->get_mx(0, dist(v)));
v = p[head[v]];
}
while (!ancestor(head[u], v)) {
ans = max(ans, tree[u]->get_mx(0, dist(u)));
u = p[head[u]];
}
if (dist(u) < dist(v)) swap(u, v);
ans = max(ans, tree[v]->get_mx(dist(v), dist(u)));
return ans;
}
intmain () {
ios::sync_with_stdio(false);
cin.tie(0);
int n;
cin >> n;
for (int i = 0; i < n-1; i++) {
int u, v;
cin >> u >> v;
u--, v--;
g[u].push_back(v);
g[v].push_back(u);
}
head[0] = 0, p[0] = -1, d[0] = 0;
dfs1(0);
dfs2(0);
int q;
cin >> q;
while (q--) {
char type;
cin >> type;
if (type == 'I') {
int v, t;
cin >> v >> t;
v--;
tree[v]->upd(dist(v), t);
}
else{
int u, v;
cin >> u >> v;
u--, v--;
cout << query(u, v) << "\n";
}
}
return0;
}