1 条题解
-
0XzyStudio (admin) LV 8 MOD RP++ tayz @ 2024-11-28 23:08:27
#include<bits/stdc++.h> #define int long long #define ls 2*k #define rs 2*k+1 #define N 500005 #define T 500005 using namespace std; int n,q; int ti[N],w[N],fa[N],son[N],dep[N],sz[N],top[N],id[N],nw[N],zs[N],cnt; vector<int> t[N]; inline int read() { int x=0,f=1; char ch=cin.get(); while(ch<'0'||ch>'9') { if(ch=='-') f=-1; ch=cin.get(); } while(ch>='0' && ch<='9') x=x*10+ch-'0',ch=cin.get(); return x*f; } //seg_begin int a[4*N]; void modify(int k,int l,int r,int ql,int qr,int num){ if(ql<=l&&qr>=r){ a[k]+=num*(r-l+1);return; } int mid=(l+r)/2; if(ql<=mid)modify(ls,l,mid,ql,qr,num); if(qr>mid)modify(rs,mid+1,r,ql,qr,num); a[k]=a[ls]+a[rs]; } int query(int k,int l,int r,int ql,int qr){ if(ql<=l&&qr>=r)return a[k]; int mid=(l+r)/2,res=0; if(ql<=mid)res=(res+query(ls,l,mid,ql,qr)); if(qr>mid)res=(res+query(rs,mid+1,r,ql,qr)); return res; } //seg_end void dfs1(int u,int fath){ fa[u]=fath;dep[u]=dep[fath]+1;sz[u]=1; for(auto i:t[u]){ if(i==fath)continue; dfs1(i,u); sz[u]+=sz[i]; if(sz[i]>sz[son[u]])son[u]=i; } } void dfs2(int u,int p){ top[u]=p;id[u]=++cnt;nw[id[u]]=w[u]; if(!son[u]){ zs[u]=cnt;return; } dfs2(son[u],p); for(auto i:t[u]){ if(i==fa[u]||i==son[u])continue; dfs2(i,i); } zs[u]=cnt; } int solve(int u,int v){ int res=0; while(top[u]!=top[v]){ if(dep[top[u]]<dep[top[v]])swap(u,v); res+=query(1,1,n,id[top[u]],id[u]); u=fa[top[u]]; } if(dep[u]<dep[v])swap(u,v); res+=query(1,1,n,id[v],id[u]); return res; } struct pt{ int id,t,w; }p[N]; struct ask{ int id,l,r,x,y,ans; }pr[N],sf[N]; bool cmp1(pt a,pt b){return a.t<b.t;} bool cmp2(ask a,ask b){return a.l<b.l;} bool cmp3(ask a,ask b){return a.r<b.r;} bool cmp4(ask a,ask b){return a.id<b.id;} signed main(){ ios::sync_with_stdio(false); n=read();q=read(); for(int i=1;i<n;i++){ int a,b;a=read();b=read(); t[a].push_back(b); t[b].push_back(a); } for(int i=1;i<=n;i++){ ti[i]=read();w[i]=read(); } dfs1(1,0); dfs2(1,1); for(int i=1;i<=n;i++){ p[i]={i,ti[i],w[i]}; } sort(p+1,p+n+1,cmp1); for(int i=1;i<=q;i++){ int l,r,x,y; l=read();r=read();x=read();y=read(); pr[i]={i,l,r,x,y,0}; sf[i]={i,l,r,x,y,0}; } sort(pr+1,pr+q+1,cmp2); sort(sf+1,sf+q+1,cmp3); for(int i=0,j=1,k=1,l=1;i<=T;i++){ while(i==p[j].t&&j<=n){ modify(1,1,n,id[p[j].id],id[p[j].id],p[j].w);j++; } while(i==pr[k].l-1&&k<=q){ pr[k].ans=solve(pr[k].x,pr[k].y);k++; } while(i==sf[l].r&&l<=q){ sf[l].ans=solve(sf[l].x,sf[l].y);l++; } } sort(pr+1,pr+q+1,cmp4); sort(sf+1,sf+q+1,cmp4); for(int i=1;i<=q;i++){ cout<<sf[i].ans-pr[i].ans<<"\n"; } }
- 1
信息
- ID
- 1096
- 难度
- 9
- 分类
- (无)
- 标签
- (无)
- 递交数
- 1
- 已通过
- 1
- 通过率
- 100%
- 上传者