ZOJ3686 A Simple Tree Problem dfs遍历+线段树

本文介绍了一种在树形结构上使用线段树进行高效查询与更新的方法。通过对树进行深度优先搜索(DFS),将其转换为线性序列,从而实现对子树的有效操作。适用于需要频繁对子树节点进行翻转操作及查询节点值和的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这道题目给出了一颗树,并且有两种操作,一种是将以节点i为root的子树每个节点上的值取反,还有一种操作时查询以节点i为root的子树所有节点上的值得和。

节点上的值不是1就是0,初始皆为0;

直接在原有的树上操作是不行了的,因为题目需要频繁的修改子树,和查询子树,因此这道题目要用线段树。

我们要先用dfs将这个树遍历,之后形成一个线性序列。

比如

            1

   2       3       4

5   6           7  8  9

 

比如这棵树 dfs遍历之后的序列  是

1 2 5 6 3 4 7 8 9

我们可以看到每一颗子树的节点都在一个区间上。利用这个就可以写成成段更新的线段树了。 

 

A Simple Tree Problem

 


 

Time Limit: 3 Seconds                                     Memory Limit: 65536 KB                            

 


 

Given a rooted tree, each node has a boolean (0 or 1) labeled on it. Initially, all the labels are 0.

We define this kind of operation: given a subtree, negate all its labels.

And we want to query the numbers of 1's of a subtree.

 

Input

Multiple test cases.

First line, two integer N and M, denoting the numbers of nodes and numbers of operations and queries.(1<=N<=100000, 1<=M<=10000)

Then a line with N-1 integers, denoting the parent of node 2..N. Root is node 1.

Then M lines, each line are in the format "o node" or "q node", denoting we want to operate or query on the subtree with root of a certain node.

 

Output

For each query, output an integer in a line.

Output a blank line after each test case.

 

Sample Input

3 2
1 1
o 2
q 1

 

Sample Output

1

 


                            Author: CUI, Tianyi
                                                    Contest: ZOJ Monthly, March 2013

 

 

#include<iostream>
#include<cstring>
#include<algorithm>
#include<cstdio>
#include<string>

using namespace std;

#define MAXN 100010
#define lson l,m,root<<1
#define rson m+1,r,root<<1|1

struct nodes
{
    int to,next;
}edge[100010];

int head[MAXN],p,e;
int l[MAXN],r[MAXN];
int node[MAXN<<2],col[MAXN<<2];

void dfs(int u)
{
    l[u]=++p;
    for(int i=head[u];i!=-1;i=edge[i].next)
        dfs(edge[i].to);
    r[u]=p;
}

void add(int a,int b) //parent: a child: b
{
    edge[e].to=b;
    edge[e].next=head[a];
    head[a]=e++;
}

void push_up(int root)
{
    node[root]=node[root<<1]+node[root<<1|1];
}

void push_down(int root,int m)
{
    if(col[root])
    {
        col[root<<1]^=1;
        col[root<<1|1]^=1;
        node[root<<1]=(m-(m>>1))-node[root<<1];
        node[root<<1|1]=(m>>1)-node[root<<1|1];
        col[root]=0;
    }
}

void build(int l,int r,int root)
{
    col[root]=0;
    if(l==r)
    {
       node[root]=0;
       return ;
    }
    int m=(l+r)>>1;
    build(lson);
    build(rson);
    push_up(root);
}

void update(int L,int R,int l,int r,int root)
{
    if(l>=L && r<=R)
    {
        col[root]^=1;
        node[root]=(r-l+1)-node[root];
        return;
    }
    int m=(l+r)>>1;
    push_down(root,r-l+1);
    if(L<=m) update(L,R,lson);
    if(R>m) update(L,R,rson);
    push_up(root);
}

int query(int L,int R,int l,int r,int root)
{
    if(l>=L && R>=r)
    {
        return node[root];
    }
    int ret=0,m=(l+r)>>1;
    push_down(root,r-l+1);
    if(L<=m) ret+=query(L,R,lson);
    if(R>m) ret+=query(L,R,rson);
    return ret;
}

int n,m,t;
char q[20];

int main()
{
    while(~scanf("%d%d",&n,&m))
    {
        build(1,n,1);
        memset(head,-1,sizeof(head)),e=0,p=0;
        for(int i=2;i<=n;i++)
        {
            scanf("%d",&t);
            add(t,i);
        }
        dfs(1);
        for(int i=0;i<m;i++)
        {
            scanf("%s%d",q,&t);
            if(q[0]=='q')
                printf("%d\n",query(l[t],r[t],1,n,1));
            else
                update(l[t],r[t],1,n,1);
        }
        printf("\n");
    }
    return 0;
}


 

### ZOJ 1088 线段树 解题思路 #### 题目概述 ZOJ 1088 是一道涉及动态维护区间的经典问题。通常情况下,这类问题可以通过线段树来高效解决。题目可能涉及到对数组的区间修改以及单点查询或者区间查询。 --- #### 线段树的核心概念 线段树是一种基于分治思想的数据结构,能够快速处理区间上的各种操作,比如求和、最大值/最小值等。其基本原理如下: - **构建阶段**:通过递归方式将原数组划分为多个小区间,并存储在二叉树形式的节点中。 - **更新阶段**:当某一段区间被修改时,仅需沿着对应路径向下更新部分节点即可完成全局调整。 - **查询阶段**:利用懒惰标记(Lazy Propagation),可以在 $O(\log n)$ 时间复杂度内完成任意范围内的计算。 具体到本题,假设我们需要支持以下两种主要功能: 1. 对指定区间 `[L, R]` 执行某种操作(如增加固定数值 `val`); 2. 查询某一位置或特定区间的属性(如总和或其他统计量)。 以下是针对此场景设计的一种通用实现方案: --- #### 实现代码 (Python) ```python class SegmentTree: def __init__(self, size): self.size = size self.tree_sum = [0] * (4 * size) # 存储区间和 self.lazy_add = [0] * (4 * size) # 延迟更新标志 def push_up(self, node): """ 更新父节点 """ self.tree_sum[node] = self.tree_sum[2*node+1] + self.tree_sum[2*node+2] def build_tree(self, node, start, end, array): """ 构建线段树 """ if start == end: # 到达叶节点 self.tree_sum[node] = array[start] return mid = (start + end) // 2 self.build_tree(2*node+1, start, mid, array) self.build_tree(2*node+2, mid+1, end, array) self.push_up(node) def update_range(self, node, start, end, l, r, val): """ 区间更新 [l,r], 加上 val """ if l <= start and end <= r: # 当前区间完全覆盖目标区间 self.tree_sum[node] += (end - start + 1) * val self.lazy_add[node] += val return mid = (start + end) // 2 if self.lazy_add[node]: # 下传延迟标记 self.lazy_add[2*node+1] += self.lazy_add[node] self.lazy_add[2*node+2] += self.lazy_add[node] self.tree_sum[2*node+1] += (mid - start + 1) * self.lazy_add[node] self.tree_sum[2*node+2] += (end - mid) * self.lazy_add[node] self.lazy_add[node] = 0 if l <= mid: self.update_range(2*node+1, start, mid, l, r, val) if r > mid: self.update_range(2*node+2, mid+1, end, l, r, val) self.push_up(node) def query_sum(self, node, start, end, l, r): """ 查询区间[l,r]的和 """ if l <= start and end <= r: # 完全匹配 return self.tree_sum[node] mid = (start + end) // 2 res = 0 if self.lazy_add[node]: self.lazy_add[2*node+1] += self.lazy_add[node] self.lazy_add[2*node+2] += self.lazy_add[node] self.tree_sum[2*node+1] += (mid - start + 1) * self.lazy_add[node] self.tree_sum[2*node+2] += (end - mid) * self.lazy_add[node] self.lazy_add[node] = 0 if l <= mid: res += self.query_sum(2*node+1, start, mid, l, r) if r > mid: res += self.query_sum(2*node+2, mid+1, end, l, r) return res def solve(): import sys input = sys.stdin.read data = input().split() N, Q = int(data[0]), int(data[1]) # 数组大小 和 操作数量 A = list(map(int, data[2:N+2])) # 初始化数组 st = SegmentTree(N) st.build_tree(0, 0, N-1, A) idx = N + 2 results = [] for _ in range(Q): op_type = data[idx]; idx += 1 L, R = map(int, data[idx:idx+2]); idx += 2 if op_type == 'Q': # 查询[L,R]的和 result = st.query_sum(0, 0, N-1, L-1, R-1) results.append(result) elif op_type == 'U': # 修改[L,R]+X X = int(data[idx]); idx += 1 st.update_range(0, 0, N-1, L-1, R-1, X) print("\n".join(map(str, results))) solve() ``` --- #### 关键点解析 1. **初始化与构建**:在线段树创建过程中,需要遍历输入数据并将其映射至对应的叶子节点[^1]。 2. **延迟传播机制**:为了优化性能,在执行批量更新时不立即作用于所有受影响区域,而是记录更改意图并通过后续访问逐步生效[^2]。 3. **时间复杂度分析**:由于每层最多只访问两个子树分支,因此无论是更新还是查询都维持在 $O(\log n)$ 范围内[^3]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值