阔力梯的树 (树上启发式合并)

题目链接: 阔力梯的树

大致题意

如题所述.

想额外提一点的是, 题目中说这个节点的子树, 是需要计算当前节点的.

解题思路

dsu on tree

读完题, 我们分析一下这个题的特点, 需要统计每个节点所有子树的情况. 那不刚好符合dsu on tree能处理的问题吗? 考虑到信息维护, 我们直接把子树的信息维护到一个set中即可.

很快, 打完了就吃了T. 因为我每次求当前子树的答案时, 我都从头到尾跑了一遍set, 思考后发现, 还不如暴力方法来的快.

考虑如何优化 我们回想一下之前的dsu on tree题目, 我们需要在遍历当前节点所有轻儿子的时候, 就求出贡献, 这样才能保证O(nlogn)的复杂度.

在遍历轻儿子的函数中(下面代码为fact函数), 我们的操作就是, 把x节点加入set中. 我们发现, 其实插入x后贡献的变化情况我们可以O(1)求出.

​ ①插入x后, x位于set最开头/结尾. 此时相当于在原有贡献的基础上, 直接加上x产生的新贡献即可.
​ ②插入x后, x位于两个已有编号中间, 此时我们需要减去原本两个编号产生的贡献, 同时在加上x和两者产生的新贡献. (若其前一个数为prev, 后一个为next, 则原本的贡献是 prev和next 产生的. 插入后变为 prev和x, x和next共同产生.)

AC代码

#include <bits/stdc++.h>
#define rep(i, n) for (int i = 1; i <= (n); ++i)
using namespace std;
typedef long long ll;
const int N = 1E5 + 10;
vector<int> edge[N];
int son[N], sz[N];

ll res[N], sum = 0;
void dfs1(int x) {
	sz[x] = 1;
	for (auto& to : edge[x]) {
		dfs1(to);
		sz[x] += sz[to];
		if (sz[to] > sz[son[x]]) son[x] = to;
	}
}

set<int> st;
void fact(int x, int pson) {
	st.insert(x);
	auto index = st.lower_bound(x);
	if (index == st.begin()) { // next --> x next
		if (next(index) != st.end()) {
			ll temp = abs(*index - *next(index));
			sum += temp * temp;
		}
	}
	else if (next(index) == st.end()) { // prev --> prev x
		if (index != st.begin()) {
			ll temp = abs(*index - *prev(index));
			sum += temp * temp;
		}
	}
	else { // prev next --> prev x next
		ll temp = abs(*next(index) - *prev(index));
		sum -= temp * temp;

		temp = abs(*next(index) - *index);
		sum += temp * temp;

		temp = abs(*prev(index) - *index);
		sum += temp * temp;
	}

	for (auto& to : edge[x]) {
		if (to == pson) continue;
		fact(to, pson);
	}
}
void dfs2(int x, int tp) {
	for (auto& to : edge[x]) {
		if (to == son[x]) continue;
		dfs2(to, 0);
	}

	if (son[x]) dfs2(son[x], 1);

	fact(x, son[x]);
	res[x] = sum;

	if (!tp) st.clear(), sum = 0;
}

int main()
{
	int n; cin >> n;
	rep(i, n - 1) {
		int x; scanf("%d", &x);
		edge[x].push_back(i + 1);
	}

	dfs1(1);
	dfs2(1, 1);

	rep(i, n) printf("%lld\n", res[i]);
	return 0;
}

END

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

逍遥Fau

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

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

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

打赏作者

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

抵扣说明:

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

余额充值