「LG4178 Tree」

题目

我终于来抄点分治的板子了

随便说一点理解吧,点分治就是一种能求某种特定树上路径数量的算法

就是选择一个分治重心,统计一下以这个重心为\(LCA\)的路径的信息

之后对这个重心的子树再次分别选择分治重心,递归下去完成统计

这道题还用了一下容斥的思想

代码

#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdio>
#define maxn 40005
#define re register
#define inf 999999999
#define LL long long
#define max(a,b) ((a)>(b)?(a):(b))
inline int read() {
	int x=0;char c=getchar();while(c<'0'||c>'9') c=getchar();
	while(c>='0'&&c<='9') x=(x<<3)+(x<<1)+c-48,c=getchar();return x;
}
struct E{int v,nxt,w;}e[maxn<<1];
int head[maxn],d[maxn],sum[maxn],mx[maxn],vis[maxn];
int n,m,num,now,tot,rt,S;LL ans;
inline void add(int x,int y,int z) {e[++num].v=y;e[num].nxt=head[x];head[x]=num;e[num].w=z;}
void getroot(int x,int fa) {
	sum[x]=1;mx[x]=0;
	for(re int i=head[x];i;i=e[i].nxt) {
		if(e[i].v==fa||vis[e[i].v]) continue;
		getroot(e[i].v,x);
		sum[x]+=sum[e[i].v];mx[x]=max(mx[x],sum[e[i].v]);
	}
	mx[x]=max(mx[x],S-sum[x]);
	if(mx[x]<now) rt=x;
}
inline void getdis(int x,int fa,int L) {
	d[++tot]=L;
	for(re int i=head[x];i;i=e[i].nxt) {
		if(e[i].v==fa||vis[e[i].v]) continue;
		getdis(e[i].v,x,L+e[i].w);
	}
}
inline void calc(int x,int len,int o) {
	tot=0;getdis(x,0,len);
	std::sort(d+1,d+tot+1);
	int l=1,r=tot;
	while(l<=r) {
		if(d[l]+d[r]<=m) {ans+=o*(r-l);l++;continue;}
		else r--;
	}
}
void dfs(int x) {
	calc(x,0,1);vis[x]=1;
	for(re int i=head[x];i;i=e[i].nxt) {
		if(vis[e[i].v]) continue;
		calc(e[i].v,e[i].w,-1);
		S=sum[e[i].v];rt=0;
		now=inf,getroot(e[i].v,0);
		dfs(rt);
	}
}
int main() {
	n=read();int x,y,z;
	for(re int i=1;i<n;i++) x=read(),y=read(),z=read(),add(x,y,z),add(y,x,z);
	m=read();now=inf,S=n,getroot(1,0);
	dfs(rt);printf("%lld\n",ans);
	return 0;
}
posted @ 2019-02-22 16:23  asuldb  阅读(124)  评论(0编辑  收藏  举报