树链剖分 80pts 关爱弱智儿童,下饭代码有助开胃

P4114 Qtree1

打完了,发现你 AC 了,没得玩了 贴一个我的树剖模板 ```cpp #include<bits/stdc++.h> using namespace std;typedef int I;const I inf=1073741824;typedef long long LL;I FL,CH;template<typename T>bool in(T&a){for(FL=1;!isdigit(CH)&&CH!=EOF;CH=getchar())if(CH=='-')FL=-1;for(a=0;isdigit(CH);CH=getchar())a=a*10+CH-'0';return a*=FL,CH==EOF?0:1;}template<typename T,typename...Args>I in(T&a,Args&...args){return in(a)+in(args...);} const I N=1e5+10; I ey[N<<1],nx[N<<1],hd[N],ec=1,n; I siz[N],dfn[N],fa[N],d[N],frt[N<<1],fri[N],tp[N<<1],hs[N],clk,idf[N],ez[N<<1],a[N]; void conn(I x,I y,I z){ ey[++ec]=y;nx[ec]=hd[x];hd[x]=ec; ez[ec]=z; }void dfs1(I x){ siz[x]=1; d[x]=d[fa[x]]+1; for(I i=hd[x],y;i;i=nx[i]){ y=ey[i]; if(y==fa[x]) continue; fa[y]=x; frt[i]=frt[i^1]=y; fri[y]=i; a[y]=ez[i]; dfs1(y); siz[x]+=siz[y]; if(siz[y]>siz[hs[x]]){ hs[x]=y; } } }void dfs2(I x,I tp){ dfn[x]=++clk; idf[clk]=x; ::tp[x]=tp; if(hs[x]){ dfs2(hs[x],tp); }for(I i=hd[x],y;i;i=nx[i]){ y=ey[i]; if(y==fa[x]||y==hs[x])continue; dfs2(y,y); } } I M[N<<1],L[N<<1],R[N<<1],cnt; void psu(I x){ M[x]=max(M[L[x]],M[R[x]]); } void build(I&p,I l,I r){ if(!p)p=++cnt; if(l==r){ M[p]=a[idf[l]]; return; }I mid=l+r>>1; build(L[p],l,mid); build(R[p],mid+1,r); psu(p); } I cp,cx,rt; void chg(I p,I l,I r){ if(l==r){ M[p]=cx; return; }I mid=l+r>>1; if(cp<=mid)chg(L[p],l,mid); if(mid<cp)chg(R[p],mid+1,r); psu(p); } I ql,qr; I qry(I p,I l,I r){ if(ql<=l&&r<=qr)return M[p]; I mid=l+r>>1; if(qr<=mid)return qry(L[p],l,mid); if(ql>mid)return qry(R[p],mid+1,r); return max(qry(L[p],l,mid),qry(R[p],mid+1,r)); } I Qry(I l,I r){ ql=l;qr=r; return qry(rt,1,n); } void pcss_chgedge(I id,I w){ cp=dfn[frt[id]]; cx=w; chg(rt,1,n); } void chgsingle(I x,I w){ cp=dfn[x]; cx=w; chg(rt,1,n); } I LCA(I x,I y){ while(tp[x]^tp[y]){ if(d[tp[x]]<d[tp[y]])x^=y^=x^=y; x=fa[tp[x]]; }return d[x]>d[y]?y:x; } I qry_path(I x,I y){ if(x==y)return 0; I lc=LCA(x,y),lcax=Qry(dfn[lc],dfn[lc]),ans=-inf; chgsingle(lc,-inf); while(tp[x]^tp[y]){ if(d[tp[x]]<d[tp[y]])swap(x,y); ans=max(ans,Qry(dfn[tp[x]],dfn[x])); x=fa[tp[x]]; }if(d[x]>d[y])swap(x,y); ans=max(ans,Qry(dfn[x],dfn[y])); chgsingle(lc,lcax); return ans; } char ops[10]; int main(){ a[1]=-inf; in(n); for(I i=1,x,y,z;i<n;++i){ in(x,y,z); conn(x,y,z); conn(y,x,z); } dfs1(1); dfs2(1,1); // printf("finished df2\n"); build(rt,1,n); I x,t; while(1){ while(!isalpha(CH))CH=getchar(); if(CH=='D')break; if(CH=='C'){ in(x,t); pcss_chgedge(x<<1,t); }else{ in(x,t); printf("%d\n",qry_path(x,t)); } } return 0; } ```
by CrTsIr400 @ 2023-01-13 21:16:42


这个码量不大,理解各变量的作用就好了,
by CrTsIr400 @ 2023-01-13 21:17:12


@[SmallTualatin](/user/121995) 好的,谢谢![](//啧.tk/mg)
by DengDuck @ 2023-01-13 21:18:14


上一页 |