前置知识
解法
观察到要维护树上信息,且更改的呈链状,考虑进行树链剖分。
将边权转化成点权,钦定边权给了深度更深的那个点,注意更新时不能更新 \(\operatorname{LCA}\)。
区间赋值和单点查询用线段树维护即可。
代码
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define ull unsigned long long
#define sort stable_sort
#define endl '\n'
struct node
{
int nxt,to;
}e[200010];
int head[200010],u[200010],v[200010],c[200010],cc[200010],siz[200010],fa[200010],dep[200010],dfn[200010],son[200010],top[200010],tot=0,cnt=0;
void add(int u,int v)
{
cnt++;
e[cnt].nxt=head[u];
e[cnt].to=v;
head[u]=cnt;
}
void dfs1(int x,int father)
{
siz[x]=1;
fa[x]=father;
dep[x]=dep[father]+1;
for(int i=head[x];i!=0;i=e[i].nxt)
{
if(e[i].to!=father)
{
dfs1(e[i].to,x);
siz[x]+=siz[e[i].to];
son[x]=(siz[e[i].to]>siz[son[x]])?e[i].to:son[x];
}
}
}
void dfs2(int x,int id)
{
top[x]=id;
tot++;
dfn[x]=tot;
cc[tot]=c[x];
if(son[x]!=0)
{
dfs2(son[x],id);
for(int i=head[x];i!=0;i=e[i].nxt)
{
if(e[i].to!=fa[x]&&e[i].to!=son[x])
{
dfs2(e[i].to,e[i].to);
}
}
}
}
struct SMT
{
struct SegmentTree
{
int l,r,sum,lazy;
}tree[800010];
int lson(int x)
{
return x*2;
}
int rson(int x)
{
return x*2+1;
}
void build(int rt,int l,int r)
{
tree[rt].l=l;
tree[rt].r=r;
tree[rt].lazy=-1;
if(l==r)
{
tree[rt].sum=cc[l];
return;
}
int mid=(l+r)/2;
build(lson(rt),l,mid);
build(rson(rt),mid+1,r);
}
void pushdown(int rt)
{
if(tree[rt].lazy!=-1)
{
tree[lson(rt)].lazy=tree[rson(rt)].lazy=tree[rt].lazy;
tree[lson(rt)].sum=tree[rson(rt)].sum=tree[rt].lazy;
tree[rt].lazy=-1;
}
}
void update(int rt,int x,int y,int val)
{
if(x<=tree[rt].l&&tree[rt].r<=y)
{
tree[rt].sum=tree[rt].lazy=val;
return;
}
pushdown(rt);
int mid=(tree[rt].l+tree[rt].r)/2;
if(x<=mid)
{
update(lson(rt),x,y,val);
}
if(y>mid)
{
update(rson(rt),x,y,val);
}
}
int query(int rt,int pos)
{
if(tree[rt].l==tree[rt].r)
{
return tree[rt].sum;
}
pushdown(rt);
int mid=(tree[rt].l+tree[rt].r)/2;
if(pos<=mid)
{
return query(lson(rt),pos);
}
else
{
return query(rson(rt),pos);
}
}
}T;
void update1(int u,int v,int val)
{
while(top[u]!=top[v])
{
if(dep[top[u]]>dep[top[v]])
{
T.update(1,dfn[top[u]],dfn[u],val);
u=fa[top[u]];
}
else
{
T.update(1,dfn[top[v]],dfn[v],val);
v=fa[top[v]];
}
}
if(dep[u]<dep[v])
{
T.update(1,dfn[u]+1,dfn[v],val);
}
else
{
T.update(1,dfn[v]+1,dfn[u],val);
}
}
int query1(int u)
{
return T.query(1,dfn[u]);
}
int main()
{
int n,m,x,y,z,i;
cin>>n>>m;
for(i=1;i<=n-1;i++)
{
cin>>u[i]>>v[i];
add(u[i],v[i]);
add(v[i],u[i]);
}
dfs1(1,0);
dfs2(1,1);
T.build(1,1,n);
for(i=1;i<=m;i++)
{
cin>>x>>y>>z;
update1(x,y,z);
}
for(i=1;i<=n-1;i++)
{
if(dep[u[i]]>dep[v[i]])
{
cout<<query1(u[i])<<endl;
}
else
{
cout<<query1(v[i])<<endl;
}
}
return 0;
}
标签:rt,lazy,筆塗,int,题解,tree,past202010,200010,son
From: https://www.cnblogs.com/The-Shadow-Dragon/p/18350307