题目分析
题目很水,理解了很简单,就是套模板。
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int maxn = 100005;
#define mid (L+R)/2
#define lson o<<1, L, mid
#define rson o<<1|1, mid+1, R
int sum[maxn<<1];
void update(int o,int L,int R,int p,int val){
if(L == R){
sum[o] = val;
return ;
}
if(p <= mid) update(lson, p, val);
else update(rson, p ,val);
sum[o] = sum[o<<1] + sum[o<<1|1];
}
int query(int o,int L,int R,int l,int r){
if(l <= L && R <= r)
return sum[o];
int ret = 0;
if(l <= mid) ret += query(lson, l, r);
if(r > mid) ret += query(rson, l ,r);
return ret;
}
struct Edge{
int to,next;
}e[maxn<<1];
int siz[maxn],fa[maxn],son[maxn],dep[maxn],top[maxn],w[maxn],head[maxn],num[maxn],cnt,tot,edge[maxn][3];
void addedge(int from,int to){
e[cnt].to = to;
e[cnt].next = head[from];
head[from] = cnt++;
}
void dfs1(int now){
siz[now] = 1;
son[now] = 0;
for(int u = head[now]; u != -1; u = e[u].next){
int v = e[u].to;
if(v != fa[now]){
dep[v] = dep[now]+1;
fa[v] = now;
dfs1(v);
siz[now] += siz[v];
if(siz[son[now]] < siz[v]) son[now] = v;
}
}
}
void dfs2(int now,int tp){
w[now] = ++tot;
top[now] = tp;
if(son[now]) dfs2(son[now], top[now]);
for(int u = head[now]; u != -1; u = e[u].next){
int v = e[u].to;
if(v != son[now] && v != fa[now])
dfs2(v, v);
}
}
int solve(int a,int b){
int f1 = top[a],f2 = top[b],ret = 0;
while(f1 != f2){
if(dep[f1] < dep[f2]){
swap(f1, f2);
swap(a, b);
}
ret += query(1, 1, tot, w[f1], w[a]);
a = fa[f1];
f1 = top[a];
}
if(a == b) return ret;
if(dep[a] > dep[b]) swap(a,b);
ret += query(1, 1, tot, w[son[a]], w[b]);
return ret;
}
void init(){
tot = cnt = 0;
memset(dep, 0, sizeof(dep));
memset(siz, 0, sizeof(siz));
memset(head, -1, sizeof(head));
memset(sum, 0, sizeof(sum));
memset(son, 0, sizeof(son));
}
int main(){
int n,q,s;
while(scanf("%d%d%d", &n, &q, &s) != EOF){
init();
for(int i = 1; i < n; i++){
scanf("%d%d%d", &edge[i][0], &edge[i][1], &edge[i][2]);
addedge(edge[i][0], edge[i][1]);
addedge(edge[i][1], edge[i][0]);
}
dfs1(1);
dfs2(1,1);
for(int i = 1; i < n; i++){
if(dep[edge[i][0]] > dep[edge[i][1]])
swap(edge[i][0], edge[i][1]);
update(1, 1, tot, w[edge[i][1]], edge[i][2]);
}
int op,a,b;
while(q--){
scanf("%d", &op);
if(op == 0){
scanf("%d", &a);
printf("%d\n", solve(s, a));
s = a;
}
else{
scanf("%d%d", &a, &b);
update(1, 1, tot, w[edge[a][1]], edge[a][2] = b);
}
}
}
return 0;
}