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

题解

被夏令营虐到痛……所以我要学点分治。

裸体,看着模板写的。不知道我的理解对不对,一些细节和原理可参考《分治算法在树的路径问题中的应用》。

#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<iostream>
#include<cmath>
#include<algorithm>
using namespace std;
int n,K,zz,head[40002],ans;
struct bian {int to,nx,v;} e[80002];
int f[40002],sum,root,son[40002],dis[40002],juli[40002];
/*
    f[]:用来求重心的数组。
	sum:记录当前树的节点总数
	root:根节点
	son[]:记录以该节点为根的子树的节点个数
	dis[]:记录该节点到当前根节点的距离。 
	juli[]:用来排序dis的数组。 
*/
bool done[40002];//判断该节点有没有被处理过 
//------------------------------------------------------------------------------
//输入建图部分 
void insert(int x,int y,int z)
{
	zz++; e[zz].to=y; e[zz].v=z; e[zz].nx=head[x]; head[x]=zz;
	zz++; e[zz].to=x; e[zz].v=z; e[zz].nx=head[y]; head[y]=zz;
}
void init()
{
	int i,x,y,z;
	scanf("%d",&n);
	for(i=1;i<n;i++)
	   {scanf("%d%d%d",&x,&y,&z);
	    insert(x,y,z);
	   }
	scanf("%d",&K);
}
//------------------------------------------------------------------------------
void getfocus(int x,int fa/*表示x节点的father,下同*/)//找重心
{
	f[x]=0; son[x]=1;
	int i,p;
	for(i=head[x];i;i=e[i].nx)
	   {p=e[i].to;
		if(p==fa||done[p]) continue;
		getfocus(p,x);
		son[x]+=son[p]; f[x]=max(f[x],son[p]);
	   }
	f[x]=max(f[x],sum-son[x]);
	if(f[x]<f[root]) root=x;
} 
/*根据重心的定义求重心,详见《分治算法在树的路径问题中的应用》 
------------------------------------------------------------------------------*/
void getdis(int x,int fa)
{
	int i,p;
	son[x]=1;
	juli[0]++; juli[juli[0]]=dis[x];
	for(i=head[x];i;i=e[i].nx)
	   {p=e[i].to;
		if(p==fa||done[p]) continue;
		dis[p]=dis[x]+e[i].v;
		getdis(p,x);
		son[x]+=son[p];
	   }
}
int cal(int x,int now)
{
	dis[x]=now; juli[0]=0;
	getdis(x,0);
	sort(juli+1,juli+juli[0]+1);
	int ct=0,l=1,r=juli[0];
	while(l<r)
	   {if(juli[l]+juli[r]<=K) {ct+=r-l; l++;}
	    else r--;
	   }
	return ct;
}
void work(int x)//求以i为根的子树中,dist(i,j)<=K的点对数。 
{
	ans+=cal(x,0);//满足Depth(i)+Depth(j)<=K的(i,j)个数 
	done[x]=1;
	int i,p;
	for(i=head[x];i;i=e[i].nx)
	   {p=e[i].to;
		if(done[p]) continue;
		ans-=cal(p,e[i].v);
		//减去满足Depth(i)+Depth(j)<=K&&Belong(i)=Belong(j)的(i,j)个数 
		sum=son[p]; f[0]=sum; root=0;
		getfocus(p,0); work(root);
	   }
	
}
//------------------------------------------------------------------------------
int main()
{
	init();
	f[0]=n; sum=n; root=0;
	getfocus(1,0);//求出全树的重心
	work(root);
	printf("%d",ans);
	return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值