[CF1076E]Vasya and a Tree

题目大意:给定一棵以$1$为根的树,$m$次操作,第$i$次为对以$v_i$为根的深度小于等于$d_i$的子树的所有节点权值加$x_i$。最后输出每个节点的值

题解:可以把操作离线,每次开始遍历到一个节点,把以它为根的操作加上,结束时把这个点的操作删去。

因为是$dfs$,所以一个点对同一深度的贡献是一定的,可以用树状数组区间加减,求前缀和。但是因为是$dfs$,完全可以把前缀和传入,就不需要树状数组了。

卡点:

C++ Code:

#include <cstdio>
#include <vector>
#include <cctype>
namespace __IO {
	namespace R {
		int x, ch;
		inline int read() {
			ch = getchar();
			while (isspace(ch)) ch = getchar();
			for (x = ch & 15, ch = getchar(); isdigit(ch); ch = getchar()) x = x * 10 + (ch & 15);
			return x;
		}
	}
}
using __IO::R::read;

#define maxn 300010

int head[maxn], cnt;
struct Edge {
	int to, nxt;
} e[maxn << 1];
inline void add(int a, int b) {
	e[++cnt] = (Edge) {b, head[a]}; head[a] = cnt;
}

int n, m;
struct Modify {
	int d, x;
	inline Modify() {}
	inline Modify(int __d, int __x) :d(__d), x(__x){}
};
std::vector<Modify> S[maxn];

long long pre[maxn], ans[maxn];
void dfs(int u, int fa = 0, int dep = 0, long long sum = 0) {
	for (std::vector<Modify>::iterator it = S[u].begin(); it != S[u].end(); it++) {
		pre[dep] += it -> x;
		if (dep + it -> d + 1 <= n) pre[dep + it -> d + 1] -= it -> x;
	}
	sum += pre[dep];
	ans[u] = sum;
	for (int i = head[u]; i; i = e[i].nxt) {
		int v = e[i].to;
		if (v != fa) dfs(v, u, dep + 1, sum);
	}
	for (std::vector<Modify>::iterator it = S[u].begin(); it != S[u].end(); it++) {
		pre[dep] -= it -> x;
		if (dep + it -> d + 1 <= n) pre[dep + it -> d + 1] += it -> x;
	}
}
int main() {
	n = read();
	for (int i = 1, a, b; i < n; i++) {
		a = read(), b = read();
		add(a, b);
		add(b, a);
	}
	m = read();
	for (int i = 1, v, d, x; i <= m; i++) {
		v = read(), d = read(), x = read();
		S[v].push_back(Modify(d, x));
	}
	dfs(1);
	for (int i = 1; i <= n; i++) {
		printf("%lld", ans[i]);
		putchar(i == n ? '\n' : ' ');
	}
	return 0;
}

  

猜你喜欢

转载自www.cnblogs.com/Memory-of-winter/p/9995403.html