BZOJ 2783 树 - 树上倍增 + 二分

传送门

分析:

对每个点都进行一次二分:将该点作为链的底端,二分链顶端所在的深度,然后倍增找到此点,通过前缀和相减求出链的权值,并更新l,r。

code

#include<bits/stdc++.h>
using namespace std;
namespace IO {
	template<typename T>
	inline void read(T &x) {
		T i = 0, f = 1;
		char ch = getchar();
		for(; (ch < '0' || ch > '9') && ch != '-'; ch = getchar());
		if(ch == '-') f = -1, ch = getchar();
		for(; ch >= '0' && ch <= '9'; ch = getchar()) i = (i << 3) + (i << 1) + (ch - '0');
		x = i * f;
	}
	template<typename T>
	inline void wr(T x) {
		if(x < 0) putchar('-'), x = -x;
		if(x > 9) wr(x / 10);
		putchar(x % 10 + '0');
	}
} using namespace IO;

const int N = 1e5 + 5;
int n, s;
vector<int> G[N];
int dep[N], fa[N][25], val[N], sum[N], ans;

inline void dfs(int u, int f) {
	fa[u][0] = f;
	dep[u] = dep[f] + 1;
	sum[u] = val[u] + sum[f];
	for(int i = 1; i <= 20; i++) fa[u][i] = fa[fa[u][i - 1]][i - 1];
	for(int e = G[u].size() - 1; e >= 0; e--) {
		int v = G[u][e];
		if(v == f) continue;
		dfs(v, u);
	}
}

inline int calc(int k, int delta) {
	int p = k;
	for(int i = 20; i >= 0; i--)
		if(delta & (1 << i)) k = fa[k][i];
	return sum[p] - sum[fa[k][0]];
}

inline void solve(int k) {
	int l = 0, r = dep[k];
	while(l <= r) {
		int mid = l + r >> 1;
		int ret = calc(k, dep[k] - mid);
//		cout<<k<<" "<<l<<" "<<r<<" "<<mid<<" "<<ret<<" "<<endl;
		if(ret == s) {
			ans++;
			return;
		} else if(ret < s) r = mid - 1;
		else l = mid + 1;
	}
}

int main() {
	freopen("h.in", "r" ,stdin);
	read(n), read(s);
	for(int i = 1; i <= n; i++) read(val[i]);
	for(int i = 1; i < n; i++) {
		int x, y;
		read(x), read(y);
		G[x].push_back(y), G[y].push_back(x);
	}
	dep[0] = -1, dfs(1, 0);
	for(int i = 1; i <= n; i++) solve(i);
	wr(ans);
	return 0;
}
posted @ 2017-11-01 18:06  CzYoL  阅读(148)  评论(0编辑  收藏  举报