洛谷 P4556 [Vani有约会]雨天的尾巴 /【模板】线段树合并
题目描述
分析
裸的线段树合并,主要为了存一下板子
代码
#include<cstdio>
#include<cstring>
#include<iostream>
inline int read(){
int x=0,fh=1;
char ch=getchar();
while(ch<'0' || ch>'9'){
if(ch=='-') fh=-1;
ch=getchar();
}
while(ch>='0' && ch<='9'){
x=(x<<1)+(x<<3)+(ch^48);
ch=getchar();
}
return x*fh;
}
const int maxn=5e6+5;
int n,m,head[maxn],tot=1;
struct asd{
int from,to,next;
}b[maxn];
void ad(int aa,int bb){
b[tot].from=aa;
b[tot].to=bb;
b[tot].next=head[aa];
head[aa]=tot++;
}
int siz[maxn],f[maxn],son[maxn],dep[maxn];
void dfs(int now,int fa){
siz[now]=1;
dep[now]=dep[fa]+1;
f[now]=fa;
for(int i=head[now];i!=-1;i=b[i].next){
int u=b[i].to;
if(u==fa) continue;
dfs(u,now);
siz[now]+=siz[u];
if(son[now]==0 || siz[u]>siz[son[now]]){
son[now]=u;
}
}
}
int tp[maxn],dfn[maxn],dfnc;
void dfs2(int now,int top){
tp[now]=top;
dfn[now]=++dfnc;
if(son[now]) dfs2(son[now],top);
for(int i=head[now];i!=-1;i=b[i].next){
int u=b[i].to;
if(u==f[now] || u==son[now]) continue;
dfs2(u,u);
}
}
int get_LCA(int xx,int yy){
while(tp[xx]!=tp[yy]){
if(dep[tp[xx]]>dep[tp[yy]]) std::swap(xx,yy);
yy=f[tp[yy]];
}
if(dep[xx]<dep[yy]) return xx;
return yy;
}
int cnt,rt[maxn],x[maxn],y[maxn],z[maxn],mmax,ans[maxn];
struct trr{
int lch,rch,val,cs;
}tr[maxn];
void push_up(int da){
if(!tr[da].lch || tr[tr[da].lch].cs<tr[tr[da].rch].cs){
tr[da].val=tr[tr[da].rch].val;
tr[da].cs=tr[tr[da].rch].cs;
} else {
tr[da].val=tr[tr[da].lch].val;
tr[da].cs=tr[tr[da].lch].cs;
}
}
int ad(int da,int l,int r,int t,int w){
if(!da) da=++cnt;
if(l==r){
tr[da].val=t;
tr[da].cs+=w;
return da;
}
int mids=(l+r)>>1;
if(t<=mids) tr[da].lch=ad(tr[da].lch,l,mids,t,w);
else tr[da].rch=ad(tr[da].rch,mids+1,r,t,w);
push_up(da);
return da;
}
int bing(int aa,int bb,int l,int r){
if(aa==0 || bb==0) return aa+bb;
if(l==r){
tr[aa].cs+=tr[bb].cs;
tr[aa].val=l;
return aa;
}
int mids=(l+r)>>1;
tr[aa].lch=bing(tr[aa].lch,tr[bb].lch,l,mids);
tr[aa].rch=bing(tr[aa].rch,tr[bb].rch,mids+1,r);
push_up(aa);
return aa;
}
void dfs3(int now){
for(int i=head[now];i!=-1;i=b[i].next){
int u=b[i].to;
if(u==f[now]) continue;
dfs3(u);
rt[now]=bing(rt[now],rt[u],1,mmax);
}
if(tr[rt[now]].cs) ans[now]=tr[rt[now]].val;
}
int main(){
memset(head,-1,sizeof(head));
n=read(),m=read();
for(int i=1;i<n;i++){
int aa,bb;
aa=read(),bb=read();
ad(aa,bb);
ad(bb,aa);
}
dfs(1,0);
dfs2(1,1);
for(int i=1;i<=m;i++){
x[i]=read(),y[i]=read(),z[i]=read();
if(z[i]>mmax) mmax=z[i];
}
for(int i=1;i<=m;i++){
int lca=get_LCA(x[i],y[i]);
rt[x[i]]=ad(rt[x[i]],1,mmax,z[i],1);
rt[y[i]]=ad(rt[y[i]],1,mmax,z[i],1);
rt[lca]=ad(rt[lca],1,mmax,z[i],-1);
if(f[lca]) rt[f[lca]]=ad(rt[f[lca]],1,mmax,z[i],-1);
}
dfs3(1);
for(int i=1;i<=n;i++){
printf("%d
",ans[i]);
}
return 0;
}