快乐树剖
#include<cstdio>
#include<cstring>
#include<algorithm>
#define rd read()
#define lson nd << 1
#define rson nd << 1 | 1
using namespace std; const int N = 1e4; int dep[N], top[N], f[N], son[N], size[N], id[N];
int q, n, head[N], tot, cnt, A[N], a[N];
int sum[N << ]; struct edge {
int nxt, to, val;
}e[N << ]; int read() {
int X = , p = ; char c = getchar();
for(; c > '' || c < ''; c = getchar()) if(c == '-') p = -;
for(; c >= '' && c <= ''; c = getchar()) X = X * + c - '';
return X * p;
} void added(int u, int v, int val) {
e[++tot].to = v;
e[tot].nxt = head[u];
e[tot].val = val;
head[u] = tot;
} void add(int u, int v, int val) {
added(u, v, val);
added(v, u, val);
} void dfs1(int u) {
size[u] = ;
for(int i = head[u]; i; i = e[i].nxt) {
int nt = e[i].to;
if(nt == f[u]) continue;
f[nt] = u; dep[nt] = dep[u] + ;
a[nt] = e[i].val;
dfs1(nt);
size[u] += size[nt];
if(size[nt] > size[son[u]]) son[u] = nt;
}
} void dfs2(int u) {
id[u] = ++cnt;
A[cnt] = a[u];
if(!son[u]) return;
top[son[u]] = top[u];
dfs2(son[u]);
for(int i = head[u]; i; i = e[i].nxt) {
int nt = e[i].to;
if(nt == f[u] || nt == son[u]) continue;
top[nt] = nt;
dfs2(nt);
}
} void update(int nd) {
sum[nd] = sum[lson] + sum[rson];
} void build(int l, int r, int nd) {
if(l == r) { sum[nd] = A[l]; return;}
int mid = (l + r) >> ;
build(l, mid, lson);
build(mid + , r, rson);
update(nd);
} int trie_sum(int L, int R, int l, int r, int nd) {
if(L <= l && r <= R) return sum[nd];
int tmp = , mid = (l + r) >> ;
if(L <= mid) tmp += trie_sum(L, R, l, mid, lson);
if(mid < R) tmp += trie_sum(L, R, mid + , r, rson);
return tmp;
} void sw(int &x, int &y) {
x ^= y, y ^= x, x ^= y;
} int query(int x, int y) {
int ans = , tmp;
for(; top[x] != top[y];) {
if(dep[top[x]] < dep[top[y]]) swap(x, y);
tmp = trie_sum(id[top[x]], id[x], , n, );
ans += tmp;
x = f[top[x]];
}
if(dep[x] < dep[y]) swap(x, y);
tmp = trie_sum(id[y], id[x], , n, );
ans += tmp - a[y];
return ans;
} int main()
{
n = rd; q = rd;
for(int i = ; i < n; ++i) {
int x = rd, y = rd, z = rd;
add(x, y, z);
}
dfs1(); dfs2();
build(, n, );
for(; q; q--) {
int x = rd, y = rd;
printf("%d\n", query(x, y));
}
}