AcWing 252. 树 点分治

Link
题意:
在这里插入图片描述
思路:
口胡一下点分治,点分治之所以能保证复杂度是他的递归层数<=log(n),是因为树的重心的性质:树的重心中的最大子树也不超过n/2,这样下去n每次都会/2所以最多不超过logn层,然后每一层的复杂度不超过n,甚至可以套一个log。
那么回到这题,运用点分治,每次找到目前子树的重心,然后不断递归求解,由于对于当前的点来说<=k的情况只有两种,一种是经过他,一种是不经过他,不经过他可以递归子树求解,经过他,可以暴力求解,暴力存储所有子树点到他的距离,然后容斥一下,也就是排除自己子树<=k的点对数。

// created by myq
#include<iostream>
#include<cstdlib>
#include<string>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<climits>
#include<cmath>
#include<cctype>
#include<stack>
#include<queue>
#include<list>
#include<vector>
#include<set>
#include<map>
#include<sstream>
#include<unordered_map>
#include<unordered_set>
using namespace std;
typedef long long ll;
#define x first
#define y second
typedef pair<int,int> pii;
const int N = 10010;
const int mod=998244353;
inline int read()
{
	int res=0;
	int f=1;
	char c=getchar();
	while(c>'9' ||c<'0')
	{
		if(c=='-')	f=-1;
		c=getchar();
	}
	while(c>='0'&&c<='9')
	{
		res=(res<<3)+(res<<1)+c-'0';
	}
	return res;
 }
 bool st[N];
 int q[N];
 int p[N];
 vector<pii>v[N]; 
 int n,K;
int getsz(int u,int fa){
	if(st[u])	return 0;
	int res=1;
	for(auto X:v[u]){
		int j=X.x;
		if(j==fa)	continue;
		res+=getsz(j,u);	
	}
	return res;
}
int getroot(int u,int fa,int &rt,int tot){
	if(st[u])	return 0;
	int maxv=0;
	int res=1;
	for(auto X:v[u]){
		int j=X.x;
		if(j==fa)	continue;
		
		int tt=getroot(j,u,rt,tot);	
		maxv=max(maxv,tt);
		res+=tt;
	}
	maxv=max(maxv,tot-res);
	if(maxv<=tot/2)
	rt=u;
	return res;
	
}
void get_dist(int u,int fa,int dis,int &sz){
	if(st[u])	return ;
	q[sz++]=dis;
	for(auto X:v[u]){
		int j=X.x;
		int w=X.y;
		if(j==fa)	continue;
		get_dist(j,u,dis+w,sz);
	}
}
int get(int p[],int sz){
    sort(p,p+sz);
	int j=-1;
	int res=0;
	for(int i=sz-1;i>=0;i--){
		while(j+1<i && p[j+1]+p[i]<=K)	j++;
		j=min(j,i-1);
		 res+=j+1;
	}	
	return res;
}
int dfs(int u,int fa){
	if(st[u])	return 0;
	
	getroot(u,-1,u,getsz(u,-1));
	st[u]=true;
	int psz=0;
	int res=0;
	for(auto X:v[u]){
		int j=X.x;
		int qsz=0;
		if(j==fa)	continue;
		get_dist(j,u,X.y,qsz);
		res-=get(q,qsz);
		for(int k=0;k<qsz;k++){
			p[psz++]=q[k];
			if(q[k]<=K)	res++;
		}
	}
	res+=get(p,psz);
	for(auto X:v[u]){
		int j=X.x;
		if(j==fa)	continue;
		res+=dfs(j,u);
	}
	return res;
	
}
int main()
{
	while(scanf("%d%d",&n,&K),n||K){
		memset(st,0,sizeof st);
		for(int i=0;i<=n;i++)	v[i].clear();
		for(int i=0;i<n-1;i++){
			int a,b,w;
// 			cin>>a>>b>>w;
            scanf("%d%d%d",&a,&b,&w);
			v[a].push_back({b,w});
			v[b].push_back({a,w});
		}
		printf("%d\n",dfs(0,-1));
	}
	return 0;

}
/**
* In every life we have some trouble
* When you worry you make it double
* Don't worry,be happy.
**/



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值