2026-1-17
分讨与的关系即可。
除在的树上为0。
为的祖先且均不在子树中为
倍增找祖先外,均为到的距离。
代码
#include<bits/stdc++.h>
using namespace std;
const int N=2e5+5;
struct{int t,rt,dep,dis,L,R,fa[25];}a[N];
struct{int to,ne,w;}b[N<<1];
int dfn,st[N<<1][20],n,tr[N<<3],siz,lg[N<<1];
struct{int lc,rc;bool cnt;}sg[N*400];
#define mid ((L+R)>>1)
void update(int& x,const int L,const int R,const int to){
if(!x) x=++siz,sg[x].cnt=1;
if(L<R) to<=mid?update(sg[x].lc,L,mid,to): update(sg[x].rc,mid+1,R,to);
}
void merge(int& x,const int y,const int L,const int R){
if(!x||!y) return x=(x|y),void();
sg[++siz]=sg[x],sg[x=siz].cnt|=sg[y].cnt;
if(L<R) merge(sg[x].lc,sg[y].lc,L,mid),merge(sg[x].rc,sg[y].rc,mid+1,R);
}
bool query(const int x,const int L,const int R,const int l,const int r){
if(!x||r<L||R<l) return 0;
if(l<=L&&R<=r) return sg[x].cnt;
return query(sg[x].lc,L,mid,l,r)|query(sg[x].rc,mid+1,R,l,r);
}
void dfs(const int x,const int fa){
a[x].dep=a[fa].dep+1,st[a[x].L=++dfn][0]=x,
a[x].fa[0]=fa,update(a[x].rt,1,n,x);
for(int t=1;t<=20&&a[x].fa[t-1];t++)
a[x].fa[t]=a[a[x].fa[t-1]].fa[t-1];
for(int i=a[x].t,y;i;i=b[i].ne) if((y=b[i].to)!=fa)
a[y].dis=a[x].dis+b[i].w,dfs(y,x),
merge(a[x].rt,a[y].rt,1,n),st[++dfn][0]=x;
a[x].R=dfn;
}
#define get(x,y) (a[x].dep<a[y].dep?x:y)
int LCA(int L,int R){
if(L>R) swap(L,R);
#define len (R-L+1)
const int x=st[L][lg[len]],y=st[R-(1<<lg[len])+1][lg[len]];
return get(x,y);
}
#define ls (x<<1)
#define rs (x<<1|1)
void build(const int x,const int L,const int R){
if(L==R) tr[x]=L;
else build(ls,L,mid),build(rs,mid+1,R),tr[x]=LCA(a[tr[ls]].L,a[tr[rs]].L);
}
int get_lca(const int x,const int L,const int R,const int l,const int r){
if((l<=L&&R<=r)) return tr[x];
if(r<=mid) return get_lca(ls,L,mid,l,r);
if(l>mid) return get_lca(rs,mid+1,R,l,r);
return LCA(a[get_lca(ls,L,mid,l,r)].L,a[get_lca(rs,mid+1,R,l,r)].L);
}
signed main(){
ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
int q;
cin>>n>>q;
for(int x,y,w,i=1,k=0;i<n;i++) cin>>x>>y>>w,
b[++k]={y,a[x].t,w},a[x].t=k,b[++k]={x,a[y].t,w},a[y].t=k;
dfs(1,0);
for(int i=2;i<=dfn;i++) lg[i]=lg[i>>1]+1;
for(int t=1;t<=20;t++) for(int i=1;i<=dfn+1-(1<<t);i++)
st[i][t]=get(st[i][t-1],st[i+(1<<(t-1))][t-1]);
build(1,1,n);
auto bound=[](int x,const int l,const int r)->int{
if(query(a[x].rt,1,n,l,r)) return x;
for(int t=20;t>=0;t--) if(a[x].fa[t])
if(!query(a[a[x].fa[t]].rt,1,n,l,r)) x=a[x].fa[t];
return a[x].fa[0];
};
for(int p,l,r,la=0,v;q--;cout<<la<<"\n"){
cin>>p>>l>>r;
p^=la,l^=la,r^=la,v=get_lca(1,1,n,l,r);
if(a[p].L<=a[v].L&&a[v].R<=a[p].R) la=a[v].dis-a[p].dis;
else if(a[v].L<=a[p].L&&a[p].R<=a[v].R) la=a[p].dis-a[bound(p,l,r)].dis;
else la=0ll+a[p].dis+a[v].dis-a[LCA(a[p].L,a[v].L)].dis*2ll;
}
}