/*I've been looking at Max for a long while.*/#include<iostream>#include<cstdio>#include<cstring>#defineMAXN 200010#defineINF 0x7fffffffusing namespacestd;intn,m,head[maxn],num,v[maxn],fa[maxn][ -],C[MAXN];intmii[maxn][ -],mxx[maxn][ -],up[maxn][ -],down[maxn][ -];structnode{intV,pre;} E[MAXN*2];intinit () {intx=0;Chars=GetChar (); while(s<'0'|| S>'9') s=GetChar (); while(s>='0'&&s<='9') {x=x*Ten+s-'0'; s=GetChar ();} returnx;}voidADD (int from,intTo ) {num++;e[num].v=to ; E[num].pre=head[ from]; head[ from]=num;}voidDfs (intNowint from,intDepintval) {fa[now][0]= from; c[now]=DEP; mii[now][0]=min (Val,v[now]); mxx[now][0]=Max (Val,v[now]); up[now][0]=max (0, v[ from]-V[now]); down[now][0]=max (0, v[now]-v[ from]); for(intI=head[now];i;i=e[i].pre) { if(e[i].v== from)Continue; Dfs (E[I].V,NOW,DEP+1, V[now]); }}voidGet_fa () { for(intj=1; j<= -; j + +) for(intI=1; i<=n;i++) {Fa[i][j]=fa[fa[i][j-1]][j-1]; MII[I][J]=min (mii[i][j-1],mii[fa[i][j-1]][j-1]); MXX[I][J]=max (mxx[i][j-1],mxx[fa[i][j-1]][j-1]); UP[I][J]=max (up[i][j-1],up[fa[i][j-1]][j-1]); UP[I][J]=max (up[i][j],mxx[fa[i][j-1]][j-1]-mii[i][j-1]); DOWN[I][J]=max (down[i][j-1],down[fa[i][j-1]][j-1]); DOWN[I][J]=max (down[i][j],mxx[i][j-1]-mii[fa[i][j-1]][j-1]); }}intLCA (intAintb) { if(c[a]<c[b]) swap (A, b); intt=c[a]-C[b]; for(intI=0; i<= -; i++) if((1<<i) &t) a=Fa[a][i]; if(a==b)returnA; for(intI= -; i>=0; i--) if(fa[a][i]!=Fa[b][i]) {a=Fa[a][i]; b=Fa[b][i]; } returnfa[a][0];}intUp_lca (intAintb) { intt=c[a]-c[b],ret=0, minner=inf; for(intI=0; i<= -; i++) if((1<<i) &t) {ret=Max (ret,up[a][i]); RET=max (ret,mxx[a][i]-Minner); Minner=min (minner,mii[a][i]); A=Fa[a][i]; } returnret;}intDown_lca (intAintBB) { intt=c[a]-c[b],ret=0, maxxer=0; for(intI=0; i<= -; i++) if((1<<i) &t) {ret=Max (ret,down[a][i]); RET=max (ret,maxxer-Mii[a][i]); Maxxer=Max (maxxer,mxx[a][i]); A=Fa[a][i]; } returnret;}intQuery_max (intAintb) { intT=c[a]-c[b],maxxer=V[a]; for(intI=0; i<= -; i++) if((1<<i) &t) {Maxxer=Max (maxxer,mxx[a][i]); A=Fa[a][i]; } returnmaxxer;}intQuery_min (intAintb) { intT=c[a]-c[b],minner=V[a]; for(intI=0; i<= -; i++) if((1<<i) &t) {Minner=min (minner,mii[a][i]); A=Fa[a][i]; } returnMinner;}intMain () {n=init (); for(intI=1; i<=n;i++) V[i]=init (); intu,v; for(intI=1; i<n;i++) {u=init (); v=init (); ADD (U,V); ADD (V,u); } memset (Mii,127,sizeof(MII)); Dfs (1,0,0,0); Get_fa (); M=init (); while(m--) {u=init (); v=init (); intAnc=LCA (U,V); //printf ("%d\n", ANC); intans=0; Ans=Max (Up_lca (U,anc), Down_lca (V,anc)); Ans=max (Ans,query_max (V,anc)-query_min (U,anc)); printf ("%d\n", ans); } return 0;}
Codevs 3305 Fruit Street Stroll Ⅱ