提交时间:2024-09-30 13:24:00
运行 ID: 32749
#include<bits/stdc++.h> #define up(i,l,r) for(int i=(l);i<=(r);++i) #define down(i,l,r) for(int i=(l);i>=(r);--i) #define pi pair<int,int> #define p1 first #define p2 second #define p_b push_back #define m_p make_pair using namespace std; typedef long long ll; inline ll read(){ ll x=0;short t=1;char ch=getchar(); while(ch<'0'||ch>'9'){if(ch=='-')t=-1;ch=getchar();} while(ch>='0'&&ch<='9')x=x*10+ch-'0',ch=getchar(); return x*t; } const int maxn=2e5+10; int n,q,dfn[maxn],top[maxn],fa[maxn],son[maxn],siz[maxn],ct,a[maxn],rnk[maxn]; vector<int>v[maxn]; void dfs(int u){ siz[u]=1; for(int x:v[u])if(x!=fa[u]){ fa[x]=u;dfs(x);siz[u]+=siz[x];if(siz[x]>siz[son[u]])son[u]=x; } }void dfs2(int u,int tp){ top[u]=tp,dfn[u]=++ct;rnk[ct]=u; if(!son[u])return; dfs2(son[u],tp); for(int x:v[u])if(x!=fa[u]&&x!=son[u])dfs2(x,x); }struct nd { int mn,mx,res; nd(){} nd(int _mn,int _mx,int _res){mn=_mn,mx=_mx,res=_res;} }; nd operator+(nd a,nd b){ return nd(min(a.mn,b.mn),max(a.mx,b.mx),max(max(a.res,b.res),b.mx-a.mn)); }struct SegTree { nd T[maxn<<2]; #define ls(p) (p<<1) #define rs(p) (p<<1|1) void pu(int p){T[p]=T[rs(p)]+T[ls(p)];} void bd(int l,int r,int p){ if(l==r){ T[p]=nd(a[rnk[l]],a[rnk[l]],0);return; }int mid=l+r>>1; bd(l,mid,ls(p)),bd(mid+1,r,rs(p));pu(p); }nd qry(int l,int r,int s,int t,int p){ if(l<=s&&t<=r)return T[p]; int mid=s+t>>1; if(r<=mid)return qry(l,r,s,mid,ls(p));if(l>mid)return qry(l,r,mid+1,t,rs(p)); nd A=qry(l,r,s,mid,ls(p)),B=qry(l,r,mid+1,t,rs(p)); return B+A; } }T; nd qry(int x,int y){ int u=top[x],v=top[y];nd ww;bool op=0; while(u!=v){ nd w=T.qry(dfn[u],dfn[x],1,n,1); if(!op)ww=w,op=1;else ww=ww+w; x=fa[u],u=top[x]; }nd w=T.qry(dfn[y],dfn[x],1,n,1); if(!op)ww=w;else ww=ww+w; return ww; } void slv(){ n=read(),q=read(); up(i,1,n-1){ int x=read(),y=read(); v[x].p_b(y),v[y].p_b(x); }up(i,1,n)a[i]=read(); dfs(1);dfs2(1,1);T.bd(1,n,1); while(q--){ int x=read(),y=read();nd w=qry(x,y); printf("%d\n",w.res); } }int main(){ //freopen("path.in","r",stdin); //freopen("path.out","w",stdout); slv(); fclose(stdin); fclose(stdout); return 0; }