1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
| #include<bits/stdc++.h> using namespace std; #define int long long void read(int &x) { x=0;int f=1;char ch=getchar(); for(;!isdigit(ch);ch=getchar()) if(ch=='-') f=-f; for(;isdigit(ch);ch=getchar()) x=x*10+ch-'0';x*=f; } void print(int x) { if(x<0) putchar('-'),x=-x; if(!x) return ;print(x/10),putchar(x%10+48); } void write(int x) {if(!x) putchar('0');else print(x);putchar('\n');} #define lf double #define ll long long #define pii pair<int,int > #define vec vector<int > #define pb push_back #define mp make_pair #define fr first #define sc second #define FOR(i,l,r) for(int i=l,i##_r=r;i<=i##_r;i++) const int maxn = 5e5+10; const int inf = 1e9; const lf eps = 1e-8; const int mod = 1e9+7; int n,q,head[maxn],tot,ans[maxn],sz[maxn]; struct edge{int to,nxt,w;}e[maxn<<1]; void ins(int u,int v,int w) {e[++tot]=(edge){v,head[u],w},head[u]=tot;} struct info {int l,r,id;}; vector<info > a[maxn]; #define ls p<<1 #define rs p<<1|1 #define mid ((l+r)>>1) struct segment_tree { int t[maxn<<2],tag[maxn<<2]; void push(int p,int v) {tag[p]+=v,t[p]+=v;} void pushdown(int p) {push(ls,tag[p]),push(rs,tag[p]),tag[p]=0;} void cov(int p,int l,int r,int x,int v) { if(l==r) return t[p]=v,void(); if(x<=mid) cov(ls,l,mid,x,v); else cov(rs,mid+1,r,x,v); t[p]=min(t[ls],t[rs]); } void modify(int p,int l,int r,int x,int y,int v) { if(x<=l&&r<=y) return push(p,v),void(); pushdown(p); if(x<=mid) modify(ls,l,mid,x,y,v); if(y>mid) modify(rs,mid+1,r,x,y,v); t[p]=min(t[ls],t[rs]); } int query(int p,int l,int r,int x,int y) { if(x<=l&&r<=y) return t[p]; int ans=1e18;pushdown(p); if(x<=mid) ans=min(ans,query(ls,l,mid,x,y)); if(y>mid) ans=min(ans,query(rs,mid+1,r,x,y)); return ans; } }T; void get(int x,int fa,int d) { int bo=1;sz[x]=1; for(int i=head[x];i;i=e[i].nxt) if(e[i].to!=fa) get(e[i].to,x,d+e[i].w),bo=0,sz[x]+=sz[e[i].to]; if(bo) T.cov(1,1,n,x,d); } void solve(int x,int fa) { for(auto t:a[x]) ans[t.id]=T.query(1,1,n,t.l,t.r); for(int v,i=head[x];i;i=e[i].nxt) { if((v=e[i].to)==fa) continue; T.modify(1,1,n,1,n,e[i].w); T.modify(1,1,n,v,v+sz[v]-1,-2*e[i].w); solve(v,x); T.modify(1,1,n,1,n,-e[i].w); T.modify(1,1,n,v,v+sz[v]-1,2*e[i].w); } } signed main() { read(n),read(q); for(int i=2,p,x;i<=n;i++) read(p),read(x),ins(i,p,x),ins(p,i,x); for(int i=1,l,r,v;i<=q;i++) read(v),read(l),read(r),a[v].pb((info){l,r,i}); memset(T.t,63,sizeof T.t); get(1,0,0),solve(1,0); for(int i=1;i<=q;i++) write(ans[i]); return 0; }
|