赛中init写漏了一行,多组样例T在第二组读入(
怪我懒得改模板。。。
#include<bits/stdc++.h> #include<stdio.h> #include<algorithm> #include<queue> #include<string.h> #include<iostream> #include<math.h> #include<set> #include<map> #include<vector> #include<iomanip> using namespace std; #define ll long long #define ull unsigned long long #define pb push_back #define FOR(a) for(int i=1;i<=a;i++) const int inf=0x3f3f3f3f; const int maxn=1e5+7; const long long mod=998244353; int n,m; int arr[maxn]; struct EDGE{ int v,nxt; }G[maxn<<2]; int head[maxn],tot; void addedge(int u,int v){ ++tot;G[tot].v=v;G[tot].nxt=head[u];head[u]=tot; } int top[maxn]; int pre[maxn]; int dep[maxn]; int num[maxn]; int p[maxn]; int fp[maxn]; int son[maxn]; int pos; void init(){ memset(head,-1,sizeof head);tot=0; memset(son,0,sizeof son);pos=0; } void dfs1(int u,int fa,int d){ dep[u]=d; pre[u]=fa; num[u]=1; for(int i=head[u];~i;i=G[i].nxt){ int v=G[i].v; if(v==fa)continue; dfs1(v,u,d+1); num[u]+=num[v]; if(son[u]==0 || num[v]>num[son[u]])son[u]=v; } } void getpos(int u,int sp){ top[u]=sp; p[u]=++pos; fp[p[u]]=u; if(!son[u])return; getpos(son[u],sp); for(int i=head[u];~i;i=G[i].nxt){ int v=G[i].v; if(v!=son[u] && v!=pre[u])getpos(v,v); } } struct NODE{ int maxx; int minn; ll sum; }ST[maxn<<2]; void pushup(int rt){ if(ST[rt<<1].maxx>ST[rt<<1|1].maxx){ ST[rt].maxx=ST[rt<<1].maxx; }else{ ST[rt].maxx=ST[rt<<1|1].maxx; } ST[rt].sum=ST[rt<<1].sum+ST[rt<<1|1].sum; } void build(int l,int r,int rt){ if(l==r){ST[rt].maxx=ST[rt].minn=ST[rt].sum=arr[fp[l]]; return; } int m=l+r>>1;build(l,m,rt<<1);build(m+1,r,rt<<1|1);pushup(rt); } ll Squery(int a,int b,int l,int r,int rt,int lim,int rlim){ ll ans=0; if(a<=l && b>=r && ST[rt].minn>=lim && ST[rt].maxx<=rlim) { return ST[rt].sum; }else if(l==r)return 0; int m=l+r>>1; if(a<=m)ans+=Squery(a,b,l,m,rt<<1,lim,rlim); if(b>m)ans+=Squery(a,b,m+1,r,rt<<1|1,lim,rlim); return ans; } ll work(int u,int v,int a,int b){//让树链st的[a,b]和出来 ll ans=0; while(top[u]!=top[v]){ if(dep[top[u]]<dep[top[v]])swap(u,v); ans+=Squery(p[top[u]],p[u],1,n,1,a,b); u=pre[top[u]]; } if(dep[u]<dep[v])swap(u,v); ans+=Squery(p[v],p[u],1,n,1,a,b); return ans; } int main(){ while(~scanf("%d%d",&n,&m)){ init(); for(int i=1;i<=n;i++){scanf("%d",&arr[i]);} for(int i=1,u,v;i<n;i++){ scanf("%d%d",&u,&v); addedge(u,v);addedge(v,u); } dfs1(1,0,0); getpos(1,1); build(1,n,1); for(int i=1,s,t,a,b;i<=m;i++){ scanf("%d%d%d%d",&s,&t,&a,&b); ll ans=work(s,t,a,b); if(i==1){ printf("%lld",ans); }else{ printf(" %lld",ans); } } puts(""); } }编程真开心啊(吃药.jpg