#include <cstdio>
#include <iostream>
#include <cstring>
#define inf 0x7fffffff
using namespace std;
const int MAXN = 100000 + 10;
inline int read() {
int x = 0, f = 1; char ch = getchar();
while(ch < '0' || ch > '9') {if(ch == '-') f = -1; ch = getchar();}
while(ch >= '0' && ch <= '9') {x = x * 10 + ch - '0'; ch = getchar();}
return x * f;
}
struct node { int to, next; }edge[MAXN * 3];
struct line { int x, y, w; }E[MAXN << 1];
int head[MAXN], cnt, n;
inline void addedge(int u, int v) {
edge[++cnt].to = v; edge[cnt].next = head[u];
head[u] = cnt;
}
int siz[MAXN], top[MAXN], son[MAXN], fa[MAXN];
int dep[MAXN], pos[MAXN], dfs_clock;
inline void init() {
cnt = dfs_clock = 0;
memset(head, 0, sizeof(head));
}
void dfs1(int u, int pre, int depth) {
son[u] = 0; siz[u] = 1; dep[u] = depth; fa[u] = pre;
for(int i = head[u]; i; i = edge[i].next) {
int v = edge[i].to;
if(v == pre) continue;
dfs1(v, u, depth + 1);
siz[u] += siz[v];
if(siz[v] > siz[son[u]]) son[u] = v;
}
}
void dfs2(int u, int pre) {
pos[u] = ++dfs_clock; top[u] = pre;
if(son[u] != 0) dfs2(son[u], top[u]);
for(int i = head[u]; i; i = edge[i].next) {
int v = edge[i].to;
if(v != son[u] && v != fa[u])
dfs2(v, v);
}
}
struct data { int l, r, val, mx; }tree[MAXN << 2];
void build_tree(int id, int l, int r) {
tree[id].l = l; tree[id].r = r;
tree[id].val = tree[id].mx = -inf;
if(l == r) return;
int mid = (l + r) >> 1;
build_tree(id << 1, l, mid);
build_tree(id << 1 | 1, mid + 1, r);
}
inline void update(int id, int x, int w) {
if(tree[id].l == tree[id].r) {
tree[id].mx = tree[id].val = w;
return;
}
int mid = (tree[id].l + tree[id].r) >> 1;
if(mid >= x) update(id << 1, x, w);
else update(id << 1 | 1, x, w);
tree[id].mx = max(tree[id << 1].mx, tree[id << 1 | 1].mx);
}
inline int query(int id, int L, int R) {
if(L <= tree[id].l && R >= tree[id].r) return tree[id].mx;
int mid = (tree[id].l + tree[id].r) >> 1;
int ans = -inf;
if(mid >= L) ans = max(ans, query(id << 1, L, R));
if(mid < R) ans = max(ans, query(id << 1 | 1, L, R));
return ans;
}
inline int lca(int x, int y) {
int ans = -inf;
while(top[x] != top[y]) {
if(dep[top[x]] < dep[top[y]]) swap(x, y);
ans = max(ans, query(1, pos[top[x]], pos[x]));
x = fa[top[x]];
}
if(dep[x] > dep[y]) swap(x, y);
if(x != y) ans = max(ans, query(1, pos[x] + 1, pos[y]));
return ans;
}
int main() {
int T = read();
while(T--) {
n = read(); init();
for(int i = 1; i < n; ++i) {
E[i].x = read(), E[i].y = read(), E[i].w = read();
addedge(E[i].x, E[i].y);
addedge(E[i].y, E[i].x);
}
dfs1(1, 1, 1); dfs2(1, 1);
build_tree(1, 2, n);
for(int i = 1; i < n; ++i) {
if(dep[E[i].x] > dep[E[i].y]) swap(E[i].x, E[i].y);
update(1, pos[E[i].y], E[i].w);
}
char str[100];
while(true) {
scanf("%s", str);
if(str[0] == 'D') break;
if(str[0] == 'Q') {
int u = read(), v = read();
printf("%d\n", lca(u, v));
}
else {
int u = read(), v = read();
update(1, pos[E[u].y], v);
}
}
printf("\n");
}
return 0;
}
树链剖分模板(spoj 375)
最新推荐文章于 2024-09-10 20:37:54 发布