给一棵树, 每条边有权值, 两种操作, 一种是将一条边的权值改变, 一种是询问u到v路径上最大的边的权值。
树链剖分模板。
#include <iostream> #include <vector> #include <cstdio> #include <cstring> #include <algorithm> #include <cmath> #include <map> #include <set> #include <string> #include <queue> #include <stack> #include <bitset> using namespace std; #define pb(x) push_back(x) #define ll long long #define mk(x, y) make_pair(x, y) #define lson l, m, rt<<1 #define mem(a) memset(a, 0, sizeof(a)) #define rson m+1, r, rt<<1|1 #define mem1(a) memset(a, -1, sizeof(a)) #define mem2(a) memset(a, 0x3f, sizeof(a)) #define rep(i, n, a) for(int i = a; i<n; i++) #define fi first #define se second typedef pair<int, int> pll; const double PI = acos(-1.0); const double eps = 1e-8; const int mod = 1e9+7; const int inf = 1061109567; const int dir[][2] = { {-1, 0}, {1, 0}, {0, -1}, {0, 1} }; const int maxn = 10005; int head[maxn*2], son[maxn], sz[maxn], deep[maxn], top[maxn], w[maxn], f[maxn], cnt, num; int edge[maxn][3], maxx[maxn<<2]; struct node { int to, nextt; }e[maxn*2]; void init() { mem1(head); num = cnt = 0; } void add(int u, int v, int w) { e[num].to = v, e[num].nextt = head[u], head[u] = num++; } void dfs1(int u, int fa) { sz[u] = 1; deep[u] = deep[fa]+1; son[u] = -1; f[u] = fa; for(int i = head[u]; ~i; i = e[i].nextt) { int v = e[i].to; if(v == fa) continue; dfs1(v, u); sz[u] += sz[v]; if(son[u]==-1||sz[v]>sz[son[u]]) son[u] = v; } } void dfs2(int u, int tp) { w[u] = ++cnt, top[u] = tp; if(~son[u]) dfs2(son[u], tp); for(int i = head[u]; ~i; i = e[i].nextt) { int v = e[i].to; if(v == f[u]||v == son[u]) continue; dfs2(v, v); } } void pushUp(int rt) { maxx[rt] = max(maxx[rt<<1], maxx[rt<<1|1]); } void update(int p, int val, int l, int r, int rt) { if(l == r) { maxx[rt] = val; return ; } int m = l+r>>1; if(p<=m) update(p, val, lson); else update(p, val, rson); pushUp(rt); } int query(int L, int R, int l, int r, int rt) { if(L<=l&&R>=r) { return maxx[rt]; } int m = l+r>>1, ret = 0; if(L<=m) ret = max(ret, query(L, R, lson)); if(R>m) ret = max(ret, query(L, R, rson)); return ret; } int find(int u, int v) { int f1 = top[u], f2 = top[v], ret = 0; while(f1 != f2) { if(deep[f1]<deep[f2]) { swap(f1, f2); swap(u, v); } ret = max(ret, query(w[f1], w[u], 1, cnt, 1)); u = f[f1]; f1 = top[u]; } if(u == v) return ret; if(deep[u]>deep[v]) swap(u, v); return max(ret, query(w[son[u]], w[v], 1, cnt, 1)); } int main() { int t, n, u, v, val; cin>>t; while(t--) { scanf("%d", &n); init(); deep[0] = 0; for(int i = 1; i<n; i++) { scanf("%d%d%d", &u, &v, &val); add(u, v, val); add(v, u, val); edge[i][0] = u, edge[i][1] = v, edge[i][2] = val; } dfs1(1, 0); dfs2(1, 1); for(int i = 1; i<n; i++) { if(deep[edge[i][0]]>deep[edge[i][1]]) { swap(edge[i][0], edge[i][1]); } update(w[edge[i][1]], edge[i][2], 1, cnt, 1); } char s[10]; while(scanf("%s", s)) { if(s[0] == ‘D‘) break; int x, y; scanf("%d%d", &x, &y); if(s[0]==‘Q‘) { printf("%d\n", find(x, y)); } else { update(w[edge[x][1]], y, 1, cnt, 1); } } } return 0; }
时间: 2024-10-17 03:06:58