题目 https://cn.vjudge.net/problem/POJ-2763
题意
求两点间距离
思路
树链剖分
JH https://jhcloud.top/blog/?p=1403
#include <algorithm>
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <map>
#include <cstring>
#include <vector>
using namespace std;
#define lson o<<1
#define rson o<<1|1
#define MID int m = (l+r)/2const int maxn = 100001 + 100;
int tree[maxn<<2];int n,m,p,s;struct edge
{int to,next;
}e[maxn*2];
int son[maxn],top[maxn],tid[maxn]; //重儿子 顶端节点 节点新编号
int siz[maxn],deep[maxn],fa[maxn]; //子树的节点数 深度 父亲节点
int data[maxn]; //节点权值
int id_data[maxn];
int U[maxn],V[maxn],W[maxn];
int _cnt,cnt; //节点编号
int head[maxn];
void add(int u,int v)
{e[cnt].to = v;e[cnt].next = head[u];head[u] = cnt++;
}
void build(int o, int l, int r)
{if(l == r){tree[o] = id_data[l];return ;}MID;build(lson, l, m);build(rson, m + 1, r);tree[o] = tree[lson] + tree[rson];
}
void updata(int o, int l, int r, int x, int d)
{if(l > x || r < x) return ;if(l == x && r == x){tree[o] = d;return ;}MID;updata(lson, l, m, x, d);updata(rson, m + 1, r, x, d);tree[o] = tree[lson] + tree[rson];
}
int query(int o, int l, int r, int ul, int ur)
{if(l > ur || r < ul) return 0;if(ul <= l && ur >= r) return tree[o];MID;return query(lson, l, m, ul, ur) + query(rson, m + 1, r, ul, ur);
}void dffs(int u, int f, int d) //点 父节点 深度
{siz[u] = 1,deep[u] = d;fa[u] = f,son[u] = -1;for(int i = head[u]; i != -1; i = e[i].next){int v = e[i].to;if(v != f) //除去父节点{dffs(v, u, d + 1);siz[u] += siz[v];if(son[u] == -1||siz[son[u]] < siz[v]) //找重儿子{son[u] = v;}}}
}
void dfss(int u,int t)
{top[u] = t,tid[u] = ++_cnt;if(son[u] != -1) dfss(son[u], t); //重儿子for(int i = head[u];i!=-1;i = e[i].next){int v = e[i].to;if(son[u] != v && fa[u] != v) dfss(v,v); //轻儿子}
}
int Query(int x, int y) {int ans = 0;int tx = top[x], ty = top[y];while (tx != ty){if (deep[tx] < deep[ty]) swap(x, y),swap(tx,ty);ans += query(1, 1, n, tid[tx], tid[x]);x = fa[tx], tx = top[x];}if(x == y) return ans;if (deep[x] > deep[y]) swap(x, y);ans += query(1, 1, n, tid[son[x]], tid[y]);return ans;
}void splite()
{_cnt = 0;dffs(1, -1, 0);//找重孩子 点信息dfss(1, 1); //剖分 (求顶端节点,新编号)
}
void init()
{memset(head,-1,sizeof(head));cnt = 0;for(int i = 1;i < n;i++){int u,v,w;scanf("%d %d %d", &u, &v, &w);add(u,v);add(v,u);U[i] = u,V[i] = v,W[i] = w;}
}
void solve()
{splite();//树链剖分for(int i=1;i<n;i++){if(deep[U[i]]<deep[V[i]]){swap(U[i],V[i]);}id_data[tid[U[i]]] = W[i];}build(1, 1, n);while(p--){int a, b, c;scanf("%d",&c);if(c == 0){scanf("%d",&a);printf("%d\n",Query(s,a));s = a;}else{scanf("%d %d", &a, &b);updata(1, 1, n, tid[U[a]], b);}}
}int main()
{scanf("%d %d %d", &n, &p, &s);init();solve();}