CF600E Lomsat gelral(线段树合并)

题目

一棵树有n个结点,每个结点都是一种颜色,每个颜色有一个编号,求树中每个子树的最多的颜色编号的和。(注意不是颜色和而是节点的编号和)

题解

  • 线段树合并的板子题
  • 这道题首先我们需要一个维护在值域范围内的线段树(权值线段树),而如果我们直接建造一棵树复杂度会非常高。 为了降低复杂度,我们可以不用建出整个线段树的结构,在我们需要时再建出我们想要的节点。这种方法维护的线段树叫做动态开点线段树。
  • 而线段树合并就是将两棵动态开点的线段树合并到一起。 合并具体操作见代码(其实很好理解
  • 对于本题来说 t [ i ] . m a x t[i].max t[i].max表示区间 i i i内颜色最多的节点个数, t [ i ] . a n s t[i].ans t[i].ans表示区间答案
  • 直接 d f s dfs dfs更新即可

code

#include <bits/stdc++.h> 
using namespace std; 
const int maxn = 1e5 + 100; 
typedef long long LL; 

template <class T> 
inline void read(T &s) {
	s = 0; T w = 1, ch = getchar(); 
	while (!isdigit(ch)) { if (ch == '-') w = -1; ch = getchar(); }
	while (isdigit(ch)) { s = (s << 1) + (s << 3) + (ch ^ 48); ch = getchar(); }
	s *= w; 
}

int n, m, tot, cnt; 
int c[maxn], lin[maxn], rt[maxn]; 
LL ans[maxn]; 
struct node {
	int next, to; 
} e[maxn << 1]; 
struct tree {
	int lc, rc, num; 
	LL ans; 
} t[maxn * 60]; 

inline void add(int from, int to) {
	e[++tot].to = to; 
	e[tot].next = lin[from]; 
	lin[from] = tot; 
}

void push_up(int p) {
	int ls = t[p].lc, rs = t[p].rc; 
	if (t[ls].num > t[rs].num) {
		t[p].num = t[ls].num; 
		t[p].ans = t[ls].ans; 
	}
	else if (t[ls].num < t[rs].num) {
		t[p].num = t[rs].num; 
		t[p].ans = t[rs].ans; 
	}
	else {
		t[p].num = t[ls].num; 
		t[p].ans = t[ls].ans + t[rs].ans; 
	}
	return ; 
}

int merge(int p, int q, int l, int r) {
	if (!p || !q) return p + q; 
	if (l == r) {
		t[p].num += t[q].num; 
		t[p].ans = l; 
		return p; 
	}
	int mid = (l + r) >> 1; 
	t[p].lc = merge(t[p].lc, t[q].lc, l, mid); 
	t[p].rc = merge(t[p].rc, t[q].rc, mid + 1, r); 
	push_up(p); 
	return p; 
}

void update(int &p, int l, int r, int x) {
	if (!p) p = ++cnt; 
	if (l == r) {
		t[p].num++; 
		t[p].ans = l; 
		return ; 
	}
	int mid = (l + r) >> 1; 
	if (x <= mid) update(t[p].lc, l, mid, x); 
	else update(t[p].rc, mid + 1, r, x); 
	push_up(p); 
}

void dfs(int u, int fa) {
	for (int i = lin[u]; i; i = e[i].next) {
		int v = e[i].to; 
		if (v == fa) continue; 
		dfs(v, u); 
		rt[u] = merge(rt[u], rt[v], 1, maxn); 
	}
	update(rt[u], 1, maxn, c[u]); 
	ans[rt[u]] = t[rt[u]].ans; 
}

int main() {
	read(n); cnt = n; 
	for (int i = 1; i <= n; ++i) {
		read(c[i]); 
		rt[i] = i; 
	}
	for (int i = 1; i < n; ++i) {
		int x, y; read(x), read(y); 
		add(x, y); add(y, x); 
	}
	dfs(1, 0); 
	for (int i = 1; i <= n; ++i) 
		printf("%lld ", ans[i]); 
	return 0; 
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值