POJ 2763

时间:2023-01-04 08:16:55

题意:给一个数,边之间有权值,然后两种操作,第一种:求任意两点的权值和,第二,修改树上两点的权值。

 #pragma comment(linker, "/STACK:1024000000,1024000000")
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
#define N 100010
#define ls o<<1
#define rs o<<1|1
#define define_m int m=(l+r)>>1
#define ll long long int first[N] , k; struct Edge{
int x , y , next , w;
Edge(){}
Edge(int x , int y , int next , int w):x(x),y(y),next(next),w(w){}
}e[N<<]; void add_edge(int x , int y , int w)
{
e[k] = Edge(x , y , first[x] , w);
first[x] = k++;
} int sz[N] , fa[N] , son[N] , dep[N] , id[N] , top[N] , num; void dfs(int u , int f , int d)
{
sz[u] = , fa[u] = f , dep[u] = d , son[u]=;
int maxn=;
for(int i=first[u] ; ~i ; i=e[i].next){
int v = e[i].y;
if(v == f) continue;
dfs(v , u , d+);
sz[u] += sz[v];
if(sz[v]>maxn) maxn=sz[v] , son[u]=v;
}
} void dfs1(int u , int f , int head)
{
top[u] = head;
id[u] = ++num;
if(son[u]){
dfs1(son[u] , u , head);
}
for(int i=first[u] ; ~i ; i=e[i].next){
int v = e[i].y;
if(v == f || v == son[u]) continue;
dfs1(v , u , v);
}
} int n , q , src , val[N] , sum[N<<]; void push_up(int o)
{
sum[o] = sum[ls]+sum[rs];
} void build(int o , int l , int r)
{
if(l==r){
sum[o] = val[l];
return;
}
define_m;
build(ls , l , m);
build(rs , m+ , r);
push_up(o);
} void update(int o , int l , int r , int p , int v)
{
if(l==r){
sum[o] = v;
return;
}
define_m;
if(m>=p) update(ls , l , m , p , v);
else update(rs , m+ , r , p , v);
push_up(o);
} int query(int o , int l , int r , int s , int t)
{
if(l>=s && r<=t) return sum[o];
define_m;
int ans = ;
if(m>=s) ans+=query(ls , l , m , s , t);
if(m<t) ans+=query(rs , m+ , r , s , t);
return ans;
} int calPath(int u , int v)
{
int top1 = top[u] , top2 = top[v];
int ans = ;
while(top1!=top2){
if(dep[top1]<dep[top2]){
swap(top1 , top2);
swap(u , v);
}
ans += query( , , num , id[top1] , id[u]);
// cout<<"range: "<<id[top1]<<" "<<id[u]<<" "<<ans<<endl;
u = fa[top1];
top1 = top[u];
}
if(u!=v){
if(dep[u]<dep[v]) swap(u , v);
ans += query( , , num , id[son[v]] , id[u]);
}
return ans;
} int main()
{
// freopen("in.txt" , "r" , stdin);
while(~scanf("%d%d%d" , &n , &q , &src)){
memset(first , - , sizeof(first));
k = ;
for(int i= ; i<n- ; i++){
int u , v , w;
scanf("%d%d%d" , &u , &v , &w);
add_edge(u , v , w);
add_edge(v , u , w);
}
num = ;
dfs( , , );
dfs1( , , );
// for(int i=1 ; i<=n ; i++) cout<<i<<" "<<son[i]<<" "<<id[i]<<endl;
for(int i= ; i<n- ; i++){
int j = i<<;
if(fa[e[j].x] != e[j].y) val[id[e[j].y]] = e[j].w;
else val[id[e[j].x]] = e[j].w;
}
build( , , num);
int en , op , t;
while(q--){
scanf("%d" , &op);
if(op){
scanf("%d%d" , &t , &en);
t--;
int pos;
if(fa[e[t*].x] != e[t*].y) pos = id[e[t*].y];
else pos = id[e[t*].x];
// cout<<"update: "<<pos<<endl;
update( , , num , pos , en);
}
else{
scanf("%d" , &en);
int ans = calPath(src , en);
printf("%d\n" ,ans);
src = en;
}
}
}
return ;
}