牛客小白月赛12 H-华华和月月种树(dfs序+差分树状数组)

本文介绍了一道使用树状数组和DFS序解决的树形DP问题,通过实例讲解了如何利用DFS序进行区间修改和单点查询,以及如何在插入节点时初始化并消除历史影响,展示了树状数组处理此类问题的优势。

题目

思路来源

官方题解

https://ac.nowcoder.com/discuss/160376?type=101&order=0&pos=5&page=1

思路来源

https://ac.nowcoder.com/acm/contest/view-submission?submissionId=40398427

题解

官方题解

先离线把所有操作都读进来,把树形建好,处理dfs序

注意到一棵子树的树根root的dfs序比其子节点都小,

且这棵子树的dfs序在[root,root+siz[root]-1]之间,所以可以区间修改加值

每次修改时,不妨对其整棵子树进行修改,

由于对某个点的查询一定是在这个点插入之后的,

所以在插入的时候再初始化即可,消除之前的影响

 

由于只有单点询问,维护差分数组的线段树,

[l,r]加v的时候,在l处加v,在r+1处减v即可,

询问x这一点的值的时候,查询[1,x]的前缀和即可

树状数组处理这类问题相当得心应手

 

然后op==1类型的操作,插入这个点,相当于给这个点初始化赋0,

那么先查询一下这个点的值v,然后令[l,l]的区间减去v即可,即起到了赋0的效果

心得

学了一年半ACM,补OI爷出的题终于有点感觉了

代码不长,却又很考验思维的题,用这些短小精悍的题提升码力再好不过了

注意时间戳dfn必须从1起,和树状数组一致

多数组的建图写法也是好评,比原来开struct edge的代码剪短了不少

也算是真正开dfs序的入门题了叭抄树链剖分板子不算

代码

#include<iostream>
#include<cstdio>
#include<cstring>
const int maxn=1e5+10;
int to[maxn],nex[maxn];
int head[maxn],num,cnt;
int siz[maxn];
int dfn[maxn];
int tree[maxn];
int n,m;
struct query
{
	int op,i,a;
}a[4*maxn];
void add(int u,int v)
{
	to[++cnt]=v;
	nex[cnt]=head[u];
	head[u]=cnt;
}
void dfs(int u)
{
	siz[u]++;
	dfn[u]=++n;
	for(int i=head[u];i;i=nex[i])
	{
		int v=to[i];
		dfs(v);
		siz[u]+=siz[v];
	}
}
void update(int x,int v)
{
	for(int i=x;i<=n;i+=i&-i)
	tree[i]+=v;
}
int ask(int x)
{
	int res=0;
	for(int i=x;i;i-=i&-i)
	res+=tree[i];
	return res;
}
int main()
{
	scanf("%d",&m);
	for(int i=1;i<=m;++i)
	{
		scanf("%d%d",&a[i].op,&a[i].i);
		if(a[i].op==2)scanf("%d",&a[i].a);
		if(a[i].op==1)
		{
			num++;
			add(a[i].i,num);
			a[i].i=num;//将1询问的结点赋为新的根节点 
		}
	}
	dfs(0);//节点可以0开头,但时间戳映射到差分BIT上一定从1开始 
	for(int i=1;i<=m;++i)
	{
		if(a[i].op==1)
		{
			int v=ask(dfn[a[i].i]);
			update(dfn[a[i].i],-v);//由于非负 子树一定大 对树根清零 子树一定非负 
			update(dfn[a[i].i]+1,v);//这里如果+1是只对树根清0 +siz[a[i].i]则对整棵树清零 
		}
		else if(a[i].op==2)
		{
			update(dfn[a[i].i],a[i].a);
			update(dfn[a[i].i]+siz[a[i].i],-a[i].a);
		}
		else printf("%d\n",ask(dfn[a[i].i]));
	}
	return 0;
}

 

### 关于牛客小白109的信息 目前并未找到关于牛客小白109的具体比信息或题解内容[^5]。然而,可以推测该事可能属于牛客网举办的系列算法竞之一,通常这类比会涉及数据结构、动态规划、图论等经典算法问题。 如果要准备类似的事,可以通过分析其他场次的比题目来提升自己的能力。例如,在牛客小白13中,有一道与二叉树相关的题目,其核心在于处理树的操作以及统计最终的结果[^3]。通过研究此类问题的解决方法,能够帮助理解如何高效地设计算法并优化时间复杂度。 以下是基于已有经验的一个通用解决方案框架用于应对类似场景下的批量更新操作: ```python class TreeNode: def __init__(self, id): self.id = id self.weight = 0 self.children = [] def build_tree(n): nodes = [TreeNode(i) for i in range(1, n + 1)] for node in nodes: if 2 * node.id <= n: node.children.append(nodes[2 * node.id - 1]) if 2 * node.id + 1 <= n: node.children.append(nodes[2 * node.id]) return nodes[0] def apply_operations(root, operations, m): from collections import defaultdict counts = defaultdict(int) def update_subtree(node, delta): stack = [node] while stack: current = stack.pop() current.weight += delta counts[current.weight] += 1 for child in current.children: stack.append(child) def exclude_subtree(node, total_nodes, delta): nonlocal root stack = [(root, False)] # (current_node, visited) subtree_size = set() while stack: current, visited = stack.pop() if not visited and current != node: stack.append((current, True)) for child in current.children: stack.append((child, False)) elif visited or current == node: if current != node: subtree_size.add(current.id) all_ids = {i for i in range(1, total_nodes + 1)} outside_ids = all_ids.difference(subtree_size.union({node.id})) for idx in outside_ids: nodes[idx].weight += delta counts[nodes[idx].weight] += 1 global nodes nodes = {} queue = [root] while queue: curr = queue.pop(0) nodes[curr.id] = curr for c in curr.children: queue.append(c) for operation in operations: op_type, x = operation.split(' ') x = int(x) target_node = nodes.get(x, None) if not target_node: continue if op_type == '1': update_subtree(target_node, 1) elif op_type == '2' and target_node is not None: exclude_subtree(target_node, n, 1) elif op_type == '3': path_to_root = [] temp = target_node while temp: path_to_root.append(temp) if temp.id % 2 == 0: parent_id = temp.id // 2 else: parent_id = (temp.id - 1) // 2 if parent_id >= 1: temp = nodes[parent_id] else: break for p in path_to_root: p.weight += 1 counts[p.weight] += 1 elif op_type == '4': pass # Implement similarly to other cases. result = [counts[i] for i in range(m + 1)] return result ``` 上述代码片段展示了针对特定类型的树形结构及其操作的一种实现方式。尽管它并非直接对应小白109中的具体题目,但它提供了一个可借鉴的设计思路。 ####
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小衣同学

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值