bzoj 1468: Tree (点分治)

1468: Tree

Time Limit: 10 Sec   Memory Limit: 64 MB
Submit: 1351   Solved: 713
[ Submit][ Status][ Discuss]

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

HINT

Source

[ Submit][ Status][ Discuss]

题解:点分治

#include<iostream>
#include<cstring>
#include<algorithm>
#include<cstdio>
#include<cmath>
#define N 100003
using namespace std;
int n,m,tot,point[N],next[N],v[N],len[N];
int d[N],deep[N],son[N],ans,k,sum,root,f[N],vis[N];
void add(int x,int y,int z)
{
	tot++; next[tot]=point[x]; point[x]=tot; v[tot]=y; len[tot]=z;
	tot++; next[tot]=point[y]; point[y]=tot; v[tot]=x; len[tot]=z;
}
void getroot(int x,int fa)
{
	f[x]=0; son[x]=1;
	for(int i=point[x];i;i=next[i]){
		if (vis[v[i]]||v[i]==fa) continue;
		getroot(v[i],x);
		son[x]+=son[v[i]];
		f[x]=max(f[x],son[v[i]]);
	}
	f[x]=max(f[x],sum-son[x]);
	if (f[x]<f[root]) root=x;
}
void getdeep(int x,int fa)
{
	deep[++deep[0]]=d[x];
	for (int i=point[x];i;i=next[i]){
		if (vis[v[i]]||v[i]==fa) continue;
		d[v[i]]=d[x]+len[i];
		getdeep(v[i],x);
	}
}
int calc(int x,int now)
{
	d[x]=now; deep[0]=0;
	getdeep(x,0);
	sort(deep+1,deep+deep[0]+1);
	int l=1; int r=deep[0];
	int t=0;
	while (l<r) {
		if (deep[l]+deep[r]<=k) t+=r-l,l++;
		else r--;
	}
	return t;
}
void work(int x)
{
	ans+=calc(x,0);
	vis[x]=1;
	for (int i=point[x];i;i=next[i]){
		if (vis[v[i]]) continue;
		ans-=calc(v[i],len[i]);
		sum=son[v[i]]; root=0;
		getroot(v[i],x);
		work(root);
	}
}
int main()
{
	freopen("a.in","r",stdin);
	scanf("%d",&n);
	for (int i=1;i<n;i++) {
		int x,y,z; scanf("%d%d%d",&x,&y,&z);
		add(x,y,z);
	}
	scanf("%d",&k);
	sum=n; f[0]=1000000000; root=0;
	getroot(1,0);
	work(root);
	printf("%d\n",ans);
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值