Simplest tree split update + segment tree Interval summation
1#include <cstdio>2#include <cstring>3#include <algorithm>4 using namespacestd;5 #defineLson l,m,rt<<16 #defineRson m+1,r,rt<<1|17 Const intMAXN =30005;8 intSIZ[MAXN],SON[MAXN],DEP[MAXN],TID[MAXN],TOP[MAXN],FA[MAXN];9 intsum[maxn<<2],VAL[MAXN];Ten inthead[maxn],cnt,lable; One structnode A { - intV,next; -}e[maxn*2]; the intN; - voidInit () - { -memset (head,-1,sizeof(head)); +CNT = lable =0; - } + voidAddintUintv) A { atE[CNT].V =v; -E[cnt].next =Head[u]; -Head[u] = cnt++; - } - voidFind_heavy (intRtintFatherintdepth) - { in intMaxSize =0; -SIZ[RT] =1; toSON[RT] =0; +FA[RT] =father; -DEP[RT] =depth; the for(inti = head[rt];i!=-1; i = e[i].next)if(e[i].v!=father) * { $Find_heavy (e[i].v,rt,depth+1);Panax Notoginsengsiz[rt]+=SIZ[E[I].V]; - if(siz[e[i].v]>maxsize) theMaxSize = Siz[e[i].v],son[rt] =e[i].v; + } A } the voidConnectintRtintANC) + { - $ //printf ("rt=%d anc=%d\n", Rt,anc); $TID[RT] = + +lable; -TOP[RT] =ANC; - if(Son[rt]) connect (SON[RT],ANC); the for(inti = head[rt];i!=-1; i =e[i].next) - if(e[i].v!=fa[rt]&&e[i].v!=Son[rt])Wuyi Connect (E[I].V,E[I].V); the } - voidPushup (intRT) Wu { -SUM[RT] = sum[rt<<1]+sum[rt<<1|1]; About } $ voidUpdateintPosintValintLintRintRT) - { - if(l==R) { -SUM[RT] =Val; A return; + } the intm = (l+r) >>1; - if(pos<=m) update (Pos,val,lson); $ ElseUpdate (Pos,val,rson); the pushup (RT); the } the intQueryintLintRintLintRintRT) the { - if(L<=L&&R<=R)returnSum[rt]; in intm = (l+r) >>1, ret =0; the if(l<=m) ret+=query (L,r,lson); the if(M<r) ret+=query (L,r,rson); About returnret; the } the int Get(intXinty) the { + intAns =0; - while(top[x]!=Top[y]) the {Bayi if(dep[top[x]]<Dep[top[y]]) swap (x, y); theAns+=query (Tid[top[x]],tid[x],1N1); thex =Fa[top[x]]; - } - if(dep[x]>Dep[y]) swap (x, y); theAns+=query (Tid[x],tid[y],1N1); the returnans; the } the intMain () - { the //freopen ("In.txt", "R", stdin); the intT;SCANF ("%d",&T); the for(intKase =1; kase<=t;++Kase)94 { the init (); thescanf"%d",&n); the for(inti =1; i<=n;++i) scanf ("%d",&val[i]);98 for(inti =1; i<n;++i) { About intU,V;SCANF ("%d%d",&u,&v); -Add (u+1, v+1); Add (v+1, u+1);101 }102Find_heavy (1,1,1);103Connect1,1);104 for(inti =1; i<=n;++i) update (Tid[i],val[i],1N1); the intM;SCANF ("%d",&m);106printf"Case %d:\n", Kase);107 while(m--)108 {109 intA,B,C;SCANF ("%d%d%d",&a,&b,&c); theb++;111 if(a) Update (TID[B],C,1N1); the Elseprintf"%d\n",Get(b,c+1));113 } the } the return 0; the}
Lightoj 1348 Aladdin and the Return Journey