【BZOJ3653】谈笑风生【主席树】【DFS序】

本文介绍了一种使用主席树解决在深度优先搜索(DFS)序区间内,深度区间内的点的贡献计算问题的方法。通过构建主席树并按DFS序插入节点,实现高效区间查询。

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

【题目链接】

发现每次询问其实相当于,问dfs序在一段区间内,深度在一段区间内的点的贡献是多少,这个是经典的二维矩形求和的问题。

因为数据比较大,考虑用主席树来维护这个信息。

我们用主席树维护深度,权值为贡献,然后按DFS序加点进去,最后区间查询就可以了。

/* Telekinetic Forest Guard */
#include <cstdio>
#include <cstring>
#include <algorithm>

using namespace std;

typedef long long LL;

const int maxn = 300005, maxm = 300005, maxnode = 7000000;

int n, m, head[maxn], cnt, depth[maxn], id[maxn], dfn[maxn], ed[maxn], size[maxn], clo;

struct _edge {
	int v, next;
} g[maxm << 1];

int root[maxn], son[maxnode][2], segcnt;
LL sum[maxnode];

inline int iread() {
	int f = 1, x = 0; char ch = getchar();
	for(; ch < '0' || ch > '9'; ch = getchar()) f = ch == '-' ? -1 : 1;
	for(; ch >= '0' && ch <= '9'; ch = getchar()) x = x * 10 + ch - '0';
	return f * x;
}

inline void add(int u, int v) {
	g[cnt] = (_edge){v, head[u]};
	head[u] = cnt++;
}

inline void dfs(int x, int f) {
	dfn[x] = ++clo;
	id[clo] = x;
	size[x] = 1;
	for(int i = head[x]; ~i; i = g[i].next) if(g[i].v ^ f) {
		depth[g[i].v] = depth[x] + 1;
		dfs(g[i].v, x);
		size[x] += size[g[i].v];
	}
	ed[x] = clo;
}

inline void insert(int last, int &now, int l, int r, int x, int c) {
	now = ++segcnt;
	sum[now] = sum[last] + c;
	if(l == r) return;
	son[now][0] = son[last][0]; son[now][1] = son[last][1];
	int mid = l + r >> 1;
	if(x <= mid) insert(son[last][0], son[now][0], l, mid, x, c);
	else insert(son[last][1], son[now][1], mid + 1, r, x, c);
}

inline LL query(int last, int now, int l, int r, int x, int y) {
	if(x <= l && r <= y) return sum[now] - sum[last];
	int mid = l + r >> 1;
	LL res = 0;
	if(x <= mid) res += query(son[last][0], son[now][0], l, mid, x, y);
	if(y > mid) res += query(son[last][1], son[now][1], mid + 1, r, x, y);
	return res;
}

int main() {
	n = iread(); m = iread();
	for(int i = 1; i <= n; i++) head[i] = -1; cnt = 0;

	for(int i = 1; i < n; i++) {
		int u = iread(), v = iread();
		add(u, v); add(v, u);
	}

	depth[1] = 1;
	dfs(1, 0);

	for(int i = 1; i <= n; i++) insert(root[i - 1], root[i], 1, n, depth[id[i]], size[id[i]] - 1);

	while(m--) {
		int x = iread(), k = iread();
		LL ans = (LL)min(k, depth[x] - 1) * (size[x] - 1);
		ans += query(root[dfn[x] - 1], root[ed[x]], 1, n, depth[x] + 1, min(depth[x] + k, n));
		printf("%lld\n", ans);
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值