HYSBZ 2243 染色 树链剖分

本文介绍了一种通过构建树状数据结构实现区间颜色更新及查询的技术。利用离线查询优化性能,通过对边界相邻区间进行特殊处理,实现了区间颜色段数的有效计算。

开始以为区间合并不可做,后来发现这个区间合并是可以的,先查询出每个区间各自颜色段数,然后对于边界相邻的边做一遍特殊处理。

传送门http://www.lydsy.com/JudgeOnline/problem.php?id=2243
#include <map>
#include <set>
#include <queue>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <algorithm>

using namespace std;

const int MAXN = 100010;

struct Edge {
    int to ;
    Edge * next;
}E[MAXN*2],*EE;

struct Gragh {
    Edge * first;
}G[MAXN];

struct Tree {
    int x,y;
    int left_color,right_color;
    int color_num;
    int lazy;
}t[MAXN<<2];

int pre[MAXN],son[MAXN],siz[MAXN],dep[MAXN],top[MAXN],pos[MAXN],Rank[MAXN];
int N,Q,S;
int num[MAXN];
int idx[MAXN];
int tree_idx = 0;
int tot ;

void Init() {
    EE = E;
    dep[1] = 1;
    pre[1] = 0;
    tree_idx = 0;
    memset(G,0,sizeof(G));
    memset(son,0,sizeof(son));
}

// void addedge(int u,int v,int value,int id) {
//     EE->to = v ; EE->next = G[u].first ; EE->value = value ; EE->id = id ; G[u].first = EE++;
//     EE->to = u ; EE->next = G[v].first ; EE->value = value ; EE->id = id ; G[v].first = EE++;
// }

void addedge(int u,int v) {
    EE->to = v ; EE->next = G[u].first ; G[u].first = EE++;
    EE->to = u ; EE->next = G[v].first ; G[v].first = EE++;
}

void dfs1(int u) {
    siz[u] = 1;
    son[u] = 0;
    for(Edge * p = G[u].first ; p ; p = p -> next) {
        if(p->to != pre[u]) {
            pre[p->to] = u;
            dep[p->to] = dep[u] + 1;
            dfs1(p->to);
            siz[u] += siz[p->to];
            if(siz[p->to] > siz[son[u]])
                son[u] = p -> to;
        }
    }
}

void dfs2(int u,int ancestor) {
    top[u] = ancestor;
    tree_idx ++;
    pos[u] = tree_idx;
    if(son[u] != 0) {
        dfs2(son[u],ancestor);
    }
    for(Edge * p = G[u].first ; p ; p = p -> next) {
        if(p->to != pre[u] && p->to != son[u]) {
            dfs2(p->to,p->to);
            // num[pos[p->to]] = p->value;
            // idx[p->id] = pos[p->to];
        }
        // else if(p->to == son[u]) {
        //     num[pos[p->to]] = p->value;
        //     idx[p->id] = pos[p->to];
        // }
    }
} 

void Push_Up(int rt) {
    if(t[rt<<1].right_color == t[rt<<1|1].left_color) {
        t[rt].color_num = t[rt<<1].color_num + t[rt<<1|1].color_num - 1;
    }
    else {
        t[rt].color_num = t[rt<<1].color_num + t[rt<<1|1].color_num; 
    }
    t[rt].right_color = t[rt<<1|1].right_color;
    t[rt].left_color = t[rt<<1].left_color;
}

void Push_Down(int rt) {
    if(t[rt].lazy) {
        t[rt<<1|1].lazy = t[rt<<1].lazy = t[rt].lazy;
        t[rt<<1].left_color = t[rt<<1].right_color = t[rt].lazy;
        t[rt<<1|1].left_color = t[rt<<1|1].right_color = t[rt].lazy;
        t[rt<<1|1].color_num = t[rt<<1].color_num = t[rt].color_num;
        t[rt].lazy = 0;
    }
}

void Build(int x,int y,int rt) {
    t[rt].x = x ; t[rt].y = y; t[rt].lazy = 0; 
    if(x == y) {
        t[rt].left_color = Rank[x];
        t[rt].right_color = Rank[x];
        t[rt].color_num = 1;
        return ;
    }
    int mid = (x + y) >> 1;
    Build(x,mid,rt<<1);
    Build(mid+1,y,rt<<1|1);
    Push_Up(rt);
}

void Update(int rt,int left,int right ,int lazy) {
   if(left <= t[rt].x && right >= t[rt].y) {
        t[rt].lazy = lazy;
        t[rt].left_color = t[rt].right_color = lazy;
        t[rt].color_num = 1;
        return ;
    }
    Push_Down(rt);
    int mid = (t[rt].x + t[rt].y) >> 1;
    if(mid >= left) {
        Update(rt<<1,left,right,lazy);
    }
    if(mid < right) {
        Update(rt<<1|1,left,right,lazy);
    }
    Push_Up(rt);
}

int right_color = 0;
int ANS = 0;

void Query(int rt,int left,int right) {
    if(left <= t[rt].x && right >= t[rt].y) {
        if(right_color == t[rt].left_color) {
            ANS = ANS + t[rt].color_num - 1;
        }
        else {
            ANS = ANS + t[rt].color_num;
        }
        right_color = t[rt].right_color;
        return ;
    }
    Push_Down(rt);
    int mid = (t[rt].x + t[rt].y) >> 1;
    // Push_Down(rt);
    if(mid >= left) {
        Query(rt<<1,left,right);
    } 
    if(mid < right){
        Query(rt<<1|1,left,right);
    }
    Push_Up(rt);
}

int Query_One(int rt,int position,int flag) {
    if(t[rt].x == t[rt].y) {
        if(flag == 0) return t[rt].left_color;
        else return t[rt].right_color;
    }
    Push_Down(rt);
    int mid = (t[rt].x + t[rt].y) >> 1;
    if(mid >= position) {
        return Query_One(rt<<1,position,flag);
    }
    else {
        return Query_One(rt<<1|1,position,flag);
    }
    Push_Up(rt);
}

void Change(int x,int y,int lazy) {
    //printf("lazy : %d\n",lazy);
    while(top[x] != top[y]) {
        if(dep[top[x]] < dep[top[y]]) swap(x,y);
        Update(1,pos[top[x]],pos[x],lazy);
        x = pre[top[x]];
    }
    if(dep[x] > dep[y]) swap(x,y);
    Update(1,pos[x],pos[y],lazy);
}

int Query_Tree(int x,int y) {
    int ans = 0;
    while(top[x] != top[y]) {
        if(dep[top[x]] < dep[top[y]]) swap(x,y);
        ANS = 0; right_color = 0;
        Query(1,pos[top[x]],pos[x]);
        ans += ANS;    
        x = pre[top[x]];
    }
    if(dep[x] > dep[y]) swap(x,y);
    ANS = 0; right_color = 0;
    Query(1,pos[x],pos[y]);
    ans += ANS;      
    return ans;
}

int inquire(int x,int y) {
    int ans = 0;
    int _left_color,_right_color;
    while(top[x] != top[y]) {
        if(dep[top[x]] < dep[top[y]]) swap(x,y);
        _left_color = Query_One(1,pos[top[x]],0);
        _right_color = Query_One(1,pos[pre[top[x]]],1);
        if(_left_color == _right_color) ans --;
        x = pre[top[x]];
    }
    return ans;
}

// void print_tree(int rt) {
//     printf("x : %d y : %d lazy : %d\n",t[rt].x,t[rt].y,t[rt].lazy);
//     if(t[rt].x == t[rt].y) {
//         printf("%d ",t[rt].value);
//         return ;
//     }
//     print_tree(rt<<1);
//     print_tree(rt<<1|1);
// }

int ReadInt() {
    char c = getchar();
    while(c > '9' || c < '0') c = getchar();
    int ret = 0;
    while(c <= '9' && c >= '0') {
        ret = ret * 10 + c - '0';
        c = getchar();
    }
    return ret;
}

void input() {
    int u,v,value;
    for(int i = 1 ; i <= N ; i++) {
        scanf("%d",num+i);
    }
    for(int i = 1 ; i <= N - 1 ; i++) {
        scanf("%d %d",&u,&v);
        addedge(u,v);
    }
    dfs1(1);
    dfs2(1,1);
    for(int i = 1 ; i <= N ; i++) {
        Rank[pos[i]] = num[i];
    }
    Build(1,N,1);
    char op[5];
    int color;
    for(int i = 1 ; i <= Q ; i ++) {
        scanf("%s",op) ;
        if(op[0] == 'C') {
            scanf("%d %d %d",&u,&v,&color);
            Change(u,v,color);
        }
        else {
            scanf("%d %d",&u,&v);
            int ans = 0;
            ans += Query_Tree(u,v);
            //printf("First_Query : %d\n",ans);
            ans += inquire(u,v);
            printf("%d\n",ans);
        }
        //print_tree(1);
        //puts("");
    }
}

int main(void) {
    freopen("a.in","r",stdin);
    while(~scanf("%d %d",&N,&Q)) {
        Init();
        input();
        //solve();
    }
    return 0;
}
### 树链剖分中的染色算法实现 树链剖分是一种高效的树形结构优化方法,常用于处理路径和子树上的复杂查询与修改操作。对于涉及染色的操作,通常可以通过树链剖分配合线段树或其他支持区间更新的数据结构来完成。 #### 基本原理 树链剖分的核心思想是将树分解为多条重链,并通过 `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)\)) ,而且易于扩展以适应更多复杂的场景需求。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值