Vijos1986
树链剖分
#include<cstdio> #include<cctype> #include<algorithm> #define maxn 100002 #define maxm 200002 using namespace std; int n,m,ne,res,val[maxn],f[maxn],dep[maxn],id[maxn],cnt,siz[maxn],top[maxn],son[maxn],fa[maxn]; int to[2*maxm],nex[2*maxm],head[maxn],tr[maxn<<2]; inline void read(int &x){ char ch=getchar();x=0; while(!isdigit(ch))ch=getchar(); while(isdigit(ch)){x=(x<<1)+(x<<3)+ch-'0';ch=getchar();} } inline void dfs1(int x,int f,int depth){ dep[x]=depth;fa[x]=f;siz[x]=1; int maxson=-1; for(int i=head[x];i;i=nex[i]){ int y=to[i]; if(y==f)continue; dfs1(y,x,depth+1); siz[x]+=siz[y]; if(siz[y]>maxson){son[x]=y;maxson=siz[y];} } } inline void dfs2(int x,int topf){ id[x]=++cnt; f[cnt]=val[x]; top[x]=topf; if(!son[x])return; dfs2(son[x],topf); for(int i=head[x];i;i=nex[i]){ int y=to[i]; if(y==fa[x]||y==son[x])continue; dfs2(y,y); } } inline void buildtr(int now,int l,int r){ if(l==r){tr[now]=f[l];return;} int mid=(l+r)>>1; buildtr(now<<1,l,mid);buildtr(now<<1|1,mid+1,r); tr[now]=tr[now<<1]+tr[now<<1|1]; } inline void updata(int now,int l,int r,int x,int w){ if(l==r){tr[now]=w;return;} int mid=(l+r)>>1; if(mid>=x)updata(now<<1,l,mid,x,w);else updata(now<<1|1,mid+1,r,x,w); tr[now]=tr[now<<1]+tr[now<<1|1]; } inline void query(int rt,int l,int r,int L,int R){ if(l>=L&&r<=R){res+=tr[rt];return;} int mid=(l+r)>>1; if(mid>=L)query(rt<<1,l,mid,L,R);if(mid<R)query(rt<<1|1,mid+1,r,L,R); } inline int qquery(int x,int y){ int ans=0; while(top[x]!=top[y]){ if(dep[top[x]]<dep[top[y]])swap(x,y); res=0;query(1,1,n,id[top[x]],id[x]); ans+=res;x=fa[top[x]]; } if(dep[x]>dep[y])swap(x,y); res=0; query(1,1,n,id[x],id[y]); ans+=res; return ans; } int main(){ read(n); for(int i=1;i<=n;i++)read(val[i]); for(int i=1;i<n;i++){ int u,v;read(u);read(v); to[++ne]=v;nex[ne]=head[u];head[u]=ne; to[++ne]=u;nex[ne]=head[v];head[v]=ne; } dfs1(1,0,1);dfs2(1,1);buildtr(1,1,n); read(m); for(int i=1;i<=m;i++){ char ch=getchar();while(ch!='Q'&&ch!='C')ch=getchar(); int u,v;read(u);read(v); if(ch=='Q')printf("%d\n",qquery(u,v));else updata(1,1,n,id[u],v); } }