【刷题】BZOJ 1468 Tree

Description

给你一棵TREE,以及这棵树上边的距离.问有多少对点它们两者间的距离小于等于K

Input

N(n<=40000) 接下来n-1行边描述管道,按照题目中写的输入 接下来是k

Output

一行,有多少对点之间的距离小于等于k

Sample Input

7
1 6 13
6 3 9
3 5 7
4 1 3
2 4 20
4 7 2
10

Sample Output

5

Solution

开始专做点分治的题目了
这就是点分治的裸题了吧
找到重心并分治之后,维护的是与根的距离
对于每个根,求的是路径经过根的两点距离小于 \(k\) 的方案数
注意去重
calc中如果有两点在同一子树内,那么它们在当前calc中信息是假的(它们本身之间的距离并没有那么大),所以在访问这个子树之前要先把多算的减掉

#include<bits/stdc++.h>
#define ui unsigned int
#define ll long long
#define db double
#define ld long double
#define ull unsigned long long
const int MAXN=40000+10,inf=0x3f3f3f3f;
int n,k,e,to[MAXN<<1],nex[MAXN<<1],beg[MAXN],w[MAXN<<1],deep[MAXN],cnt,Msonsize[MAXN],size[MAXN],d[MAXN],root,finish[MAXN];
template<typename T> inline void read(T &x)
{
	T data=0,w=1;
	char ch=0;
	while(ch!='-'&&(ch<'0'||ch>'9'))ch=getchar();
	if(ch=='-')w=-1,ch=getchar();
	while(ch>='0'&&ch<='9')data=((T)data<<3)+((T)data<<1)+(ch^'0'),ch=getchar();
	x=data*w;
}
template<typename T> inline void write(T x,char ch='\0')
{
	if(x<0)putchar('-'),x=-x;
	if(x>9)write(x/10);
	putchar(x%10+'0');
	if(ch!='\0')putchar(ch);
}
template<typename T> inline void chkmin(T &x,T y){x=(y<x?y:x);}
template<typename T> inline void chkmax(T &x,T y){x=(y>x?y:x);}
template<typename T> inline T min(T x,T y){return x<y?x:y;}
template<typename T> inline T max(T x,T y){return x>y?x:y;}
inline void insert(int x,int y,int z)
{
	to[++e]=y;
	nex[e]=beg[x];
	beg[x]=e;
	w[e]=z;
}
inline void getroot(int x,int f,int ntotal)
{
	Msonsize[x]=0;size[x]=1;
	for(register int i=beg[x];i;i=nex[i])
		if(to[i]==f||finish[to[i]])continue;
		else
		{
			getroot(to[i],x,ntotal);
			size[x]+=size[to[i]];
			chkmax(Msonsize[x],size[to[i]]);
		}
	chkmax(Msonsize[x],ntotal-size[x]);
	if(Msonsize[x]<Msonsize[root])root=x;
}
inline void getdeep(int x,int f)
{
	deep[++cnt]=d[x];
	for(register int i=beg[x];i;i=nex[i])
		if(to[i]==f||finish[to[i]])continue;
		else d[to[i]]=d[x]+w[i],getdeep(to[i],x);
}
inline int calc(int x,int st)
{
	d[x]=st;cnt=0;
	getdeep(x,0);
	std::sort(deep+1,deep+cnt+1);
	int l=1,r=cnt,ans=0;
	while(l<r)
	{
		if(deep[l]+deep[r]<=k)ans+=r-l,l++;
		else r--;
	}
	return ans;
}
inline int solve(int x)
{
	int res=calc(x,0);
	finish[x]=1;
	for(register int i=beg[x];i;i=nex[i])
		if(!finish[to[i]])
		{
			res-=calc(to[i],w[i]);
			root=0;
			getroot(to[i],x,size[to[i]]);
			res+=solve(root);
		}
	return res;
}
int main()
{
	read(n);
	for(register int i=1;i<n;++i)
	{
		int u,v,w;
		read(u);read(v);read(w);
		insert(u,v,w);insert(v,u,w);
	}
	read(k);
	Msonsize[0]=inf;root=0;
	getroot(1,0,n);
	write(solve(root),'\n');
	return 0;
}
posted @ 2018-04-12 11:23  HYJ_cnyali  阅读(178)  评论(0编辑  收藏  举报