染色 - HYSBZ 2243 树链刨分

树链剖分算法实现

染色

Time Limit: 20 Sec   Memory Limit: 512 MB
Submit: 3626   Solved: 1380
[ Submit][ Status][ Discuss]

Description

给定一棵有n个节点的无根树和m个操作,操作有2类:

1、将节点a到节点b路径上所有点都染成颜色c

2、询问节点a到节点b路径上的颜色段数量(连续相同颜色被认为是同一段),如“1122213段组成:“11、“222和“1

请你写一个程序依次完成这m个操作。

Input

第一行包含2个整数nm,分别表示节点数和操作数;

第二行包含n个正整数表示n个节点的初始颜色

下面 行每行包含两个整数xy,表示xy之间有一条无向边。

下面 行每行描述一个操作:

“C a b c”表示这是一个染色操作,把节点a到节点b路径上所有点(包括ab)都染成颜色c

“Q a b”表示这是一个询问操作,询问节点a到节点b(包括ab)路径上的颜色段数量。

Output

对于每个询问操作,输出一行答案。

Sample Input

6 5

2 2 1 2 1 1

1 2

1 3

2 4

2 5

2 6

Q 3 5

C 2 1 1

Q 3 5

C 5 1 2

Q 3 5

Sample Output

3

1

2

HINT

数N<=10^5,操作数M<=10^5,所有的颜色C为整数且在[0, 10^9]之间。


思路:树链刨分,就是线段树敲起来比较麻烦,每次查询一个区间有多少段,并且记录这个区间的左右端点值,然后把这个路径上的这些区间的查询结果放在一个vector里面,再依次判断他们的相邻部分是否相同。

AC代码如下:

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<vector>
using namespace std;
struct node
{
    int u,v;
}arr[100010];
struct node2
{
    int u,v,next;
}edge[200010];
struct node3
{
    int l,r,part,lazy,L,R;
}tree[400010];
struct node4
{
    int part,L,R;
};
vector<node4> vc1,vc2;
node4 A,B;
int T,t,n,m,tot,tot2,Head[100010];
int siz[100010],son[100010],fa[100010],depth[100010],top[100010],p[100010];
int c[100010],c2[100010];
char s[10];
void add(int u,int v)
{
    edge[tot].u=u;
    edge[tot].v=v;
    edge[tot].next=Head[u];
    Head[u]=tot++;
}
void dfs1(int u)
{
    int i,j,k,v;
    siz[u]=1;
    son[u]=0;
    for(i=Head[u];i!=-1;i=edge[i].next)
    {
        v=edge[i].v;
        if(v==fa[u])
          continue;
        fa[v]=u;
        depth[v]=depth[u]+1;
        dfs1(v);
        if(siz[v]>siz[son[u]])
          son[u]=v;
        siz[u]+=siz[v];
    }
}
void dfs2(int u,int f)
{
    int i,j,v;
    p[u]=++tot2;
    top[u]=f;
    if(son[u]!=0)
      dfs2(son[u],f);
    for(i=Head[u];i!=-1;i=edge[i].next)
    {
        v=edge[i].v;
        if(v==fa[u] || v==son[u])
          continue;
        dfs2(v,v);
    }
}
void op(int tr,int num)
{
    tree[tr].lazy=num;
    tree[tr].part=1;
    tree[tr].L=tree[tr].R=num;
}
void up(int tr)
{
    tree[tr].part=tree[tr*2].part+tree[tr*2+1].part;
    if(tree[tr*2].R==tree[tr*2+1].L)
      tree[tr].part--;
    tree[tr].L=tree[tr*2].L;
    tree[tr].R=tree[tr*2+1].R;
}
void down(int tr)
{
    if(tree[tr].lazy>=0)
    {
        op(tr*2,tree[tr].lazy);
        op(tr*2+1,tree[tr].lazy);
        tree[tr].lazy=-1;
    }
}
void build(int l,int r,int tr)
{
    tree[tr].l=l;
    tree[tr].r=r;
    tree[tr].lazy=-1;
    if(l==r)
    {
        op(tr,c2[l]);
        return;
    }
    int mi=(l+r)/2;
    build(l,mi,tr*2);
    build(mi+1,r,tr*2+1);
    up(tr);
}
void update(int l,int r,int tr,int num)
{
    if(tree[tr].l==l && tree[tr].r==r)
    {
        op(tr,num);
        return;
    }
    down(tr);
    int mi=(tree[tr].l+tree[tr].r)/2;
    if(r<=mi)
      update(l,r,tr*2,num);
    else if(l>mi)
      update(l,r,tr*2+1,num);
    else
    {
        update(l,mi,tr*2,num);
        update(mi+1,r,tr*2+1,num);
    }
    up(tr);
}
void query(int l,int r,int tr,int &part,int &L,int &R)
{
    if(tree[tr].l==l && tree[tr].r==r)
    {
        part=tree[tr].part;
        L=tree[tr].L;
        R=tree[tr].R;
        return;
    }
    down(tr);
    int mi=(tree[tr].l+tree[tr].r)/2;
    if(r<=mi)
      query(l,r,tr*2,part,L,R);
    else if(l>mi)
      query(l,r,tr*2+1,part,L,R);
    else
    {
        int part1,part2,L1,L2,R1,R2;
        query(l,mi,tr*2,part1,L1,R1);
        query(mi+1,r,tr*2+1,part2,L2,R2);
        part=part1+part2;
        if(R1==L2)
          part--;
        L=L1;
        R=R2;
    }
}
void solve_c(int u,int v,int num)
{
    int f1=top[u],f2=top[v];
    while(f1!=f2)
    {
        if(depth[f1]<depth[f2])
        {
            swap(f1,f2);
            swap(u,v);
        }
        update(p[f1],p[u],1,num);
        u=fa[f1];
        f1=top[u];
    }
    if(depth[u]>depth[v])
      swap(u,v);
    update(p[u],p[v],1,num);
}
int solve_q(int u,int v)
{
    vc1.clear();
    vc2.clear();
    int f1=top[u],f2=top[v],i,j,k,part,L,R;
    while(f1!=f2)
    {
        if(depth[f1]>depth[f2])
        {
            query(p[f1],p[u],1,A.part,A.R,A.L);
            vc1.push_back(A);
            u=fa[f1];
            f1=top[u];
        }
        else
        {
            query(p[f2],p[v],1,A.part,A.L,A.R);
            vc2.push_back(A);
            v=fa[f2];
            f2=top[v];
        }
    }
    if(depth[v]>=depth[u])
    {
        query(p[u],p[v],1,A.part,A.L,A.R);
        vc1.push_back(A);
    }
    else
    {
        query(p[v],p[u],1,A.part,A.R,A.L);
        vc1.push_back(A);
    }
    for(i=vc2.size()-1;i>=0;i--)
       vc1.push_back(vc2[i]);
    part=vc1[0].part;
    R=vc1[0].R;
    for(i=1;i<vc1.size();i++)
    {
        part+=vc1[i].part;
        if(R==vc1[i].L)
          part--;
        R=vc1[i].R;
    }
    return part;
}
int main()
{
    int i,j,k,u,v,num;
    while(~scanf("%d%d",&n,&m))
    {
        memset(Head,-1,sizeof(Head));
        tot=tot2=0;
        for(i=1;i<=n;i++)
           scanf("%d",&c[i]);
        for(i=1;i<n;i++)
        {
            scanf("%d%d",&u,&v);
            add(u,v);
            add(v,u);
        }
        depth[1]=1;
        dfs1(1);
        dfs2(1,1);
        for(i=1;i<=n;i++)
           c2[p[i]]=c[i];
        build(1,tot2,1);
        while(m--)
        {
            scanf("%s",s+1);
            if(s[1]=='C')
            {
                scanf("%d%d%d",&u,&v,&num);
                solve_c(u,v,num);
            }
            else
            {
                scanf("%d%d",&u,&v);
                num=solve_q(u,v);
                printf("%d\n",num);
            }
        }
    }
}



### 树链剖分中的染色算法实现 树链剖分是一种高效的树形结构优化方法,常用于处理路径和子树上的复杂查询与修改操作。对于涉及染色的操作,通常可以通过树链剖分配合线段树或其他支持区间更新的数据结构来完成。 #### 基本原理 树链剖分的核心思想是将树分解为多条重链,并通过 `dfn` 编号将其映射到一维数组上[^1]。这样可以方便地使用线段树等数据结构维护这些重链的属性。具体来说: - **重儿子**:每个节点的儿子中,子树大小最大的称为该节点的重儿子。 - **重链**:从某个节点出发沿着重儿子一路向下形成的链条称为重链。 - **轻边**:连接当前节点与其非重儿子的边称为轻边。 通过对树进行上述划分后,任意两点间的路径都可以被划分为不超过 \( O(\log n) \) 条重链和轻边[^2]。 #### 染色问题的具体实现 针对题目描述中的染色问题,我们需要设计一种能够高效执行以下两类操作的方法: 1. 修改路径上的所有点的颜色。 2. 查询某路径上的颜色段数。 以下是具体的解决方案及其代码实现。 --- ##### 数据结构的选择 为了快速响应路径上的批量修改以及统计颜色段的数量,可以选择如下组合: - 使用 **线段树** 维护每条重链上的信息。 - 对于颜色段计数问题,可以在每个线段树节点存储额外的状态变量,比如左端点颜色、右端点颜色、总颜色段数目等。 --- ##### 关键状态定义 假设我们已经完成了树链剖分并构建好了对应的线段树,则需要在线段树节点中记录以下几个字段: - `sum`: 当前区间的颜色段总数。 - `left_color`: 当前区间的左端点颜色。 - `right_color`: 当前区间的右端点颜色。 - `lazy_tag`: 表示是否有延迟标记(即整个区间是否已被统一染成某种颜色)。 当存在懒惰标记时,表示整段已经被覆盖为同种颜色,此时可以直接忽略其内部细节而仅保留两端的颜色信息。 --- ##### 更新逻辑 在执行路径染色的过程中,需要注意以下几点: 1. 如果目标路径跨越多个重链,则需分别对各部分单独处理; 2. 若遇到带有懒惰标记的节点,在下推之前应先清除原有标签的影响; 3. 合并两个相邻片段的结果时,要特别注意它们之间是否存在边界效应——即两者的末端颜色是否一致会影响最终计算得到的颜色段数量。 下面给出完整的伪代码实现: ```python class SegmentTreeNode: def __init__(self, l=0, r=0): self.l = l # 左边界 self.r = r # 右边界 self.sum = 0 # 颜色段数 self.left_color = None # 左端点颜色 self.right_color = None # 右端点颜色 self.lazy_tag = -1 # 懒惰标记 (-1 表示无) def push_up(node): """合并左右孩子信息""" if node.left_child.right_color == node.right_child.left_color: node.sum = node.left_child.sum + node.right_child.sum - 1 else: node.sum = node.left_child.sum + node.right_child.sum node.left_color = node.left_child.left_color node.right_color = node.right_child.right_color def build_tree(tree, idx, l, r): tree[idx].l = l tree[idx].r = r if l == r: # 初始化叶子结点 tree[idx].left_color = colors[l] tree[idx].right_color = colors[l] tree[idx].sum = 1 return mid = (l + r) >> 1 build_tree(tree, idx * 2, l, mid) build_tree(tree, idx * 2 + 1, mid + 1, r) push_up(tree[idx]) def update_range(tree, idx, L, R, color): """区间 [L,R] 的全部元素改为指定颜色 'color' """ if tree[idx].l >= L and tree[idx].r <= R: # 完全包含的情况 tree[idx].left_color = tree[idx].right_color = color tree[idx].sum = 1 tree[idx].lazy_tag = color return if tree[idx].lazy_tag != -1: # 下传懒惰标记 propagate_lazy(tree, idx) mid = (tree[idx].l + tree[idx].r) >> 1 if L <= mid: update_range(tree, idx * 2, L, R, color) if R > mid: update_range(tree, idx * 2 + 1, L, R, color) push_up(tree[idx]) # 自底向上重新计算父节点信息 def query_colors(tree, idx, L, R): """查询区间 [L,R] 上的颜色段数""" if tree[idx].l >= L and tree[idx].r <= R: return tree[idx].sum if tree[idx].lazy_tag != -1: # 下传懒惰标记 propagate_lazy(tree, idx) res = 0 mid = (tree[idx].l + tree[idx].r) >> 1 if L <= mid: res += query_colors(tree, idx * 2, L, R) if R > mid: res += query_colors(tree, idx * 2 + 1, L, R) return res def propagate_lazy(tree, idx): """传播懒惰标记至子节点""" lazy_val = tree[idx].lazy_tag if lazy_val != -1: tree[idx * 2].left_color = tree[idx * 2].right_color = lazy_val tree[idx * 2].sum = 1 tree[idx * 2].lazy_tag = lazy_val tree[idx * 2 + 1].left_color = tree[idx * 2 + 1].right_color = lazy_val tree[idx * 2 + 1].sum = 1 tree[idx * 2 + 1].lazy_tag = lazy_val tree[idx].lazy_tag = -1 ``` 以上代码展示了如何基于线段树实现在树链剖分框架下的路径染色功能[^4]。 --- #### 总结 通过结合树链剖分与线段树技术,我们可以优雅地解决诸如路径染色等问题。这种方法不仅具有较高的时间效率 (\(O(\log^2 n)\)) ,而且易于扩展以适应更多复杂的场景需求。 ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值