跳到正文

个人记录

一个点分治好题

CJ_Alexander约 6 分钟
原文
文章信息与版本

文章信息

收录
2025年12月29日
更新
2025年12月29日
篇幅
约 6 分钟

版本

  1. v2当前
  2. v1

题目传送门

这是一个平平凡凡很不错的点分治题,可以帮助初学者加深对点分治算法的了解程度。

题目描述

给定一棵 n 个节点的树,每条边有边权,求出树上两点距离小于等于 k 的点对数量

输入格式

第一行输入一个整数 n,表示节点个数。

第二行到第 n 行每行输入三个整数 u,v,w ,表示 u 与 v 有一条边,边权是 w。

第 n+1行一个整数 k 。

输出格式

一行一个整数,表示答案


这个题目个人觉得没有紫题的难度,因为我觉得他比身为蓝题的CF161D Distance in Tree 简单。

如果还不会点分治的朋友们请出门右转翻至蓝本p230-p232.

你学会后会发现,这就是一个点分治的裸题,这里提供一下用双指针查找小于等于k的点对数量的方法。

C++
int Calc(int p,int w)
{
	cnt = 0;
	get_dis(p,0,w);
	sort(dis+1,dis+1+cnt);//把找到的子节点到当前重心的距离按升序排序
	int l = 1,r = cnt,res = 0;
	while(l <= r)//双指针扫描
	{
		if(dis[l] + dis[r] <= k) res += r-l,l++;
		//因为按升序排列,所以一旦dis[r]+dis[l]<=k,那么dis[r-1]+dis[l],dis[r-2]+dis[l]都会<=k
		else r--;
	}
	return res;
}

但是有些人可能觉得:这里是不是需要特判一下两个节点在同一个子树的情况呢?这里我将会引出两种办法。

一种是特判法,但是在这个题中不适合使用。

另一种就是容斥法。顾名思义,就是运用容斥原理来去重,我们只需要把原来算出的答案减去子树中得到的答案即可

C++
void solve(int now)
{
	ans += Calc(now,0);//当前重心统计答案
	vis[now] = 1;
	for(int i = head[now];i;i = edge[i].next)
	{
		int to = edge[i].to;
		if(vis[to]) continue;
		ans -= Calc(to,edge[i].dis);//去掉在同一子树加上的非法答案
		rt = 0,MX = inf;
		get_root(to,now,sz[to]);
		solve(rt);
	}
}

这个题目到这里就完美地做完了,因为其他的步骤基本上所有点分治的题目都是那么写的,我就不再赘述。

Code我知道你们只看这个

C++
#include<bits/stdc++.h>
using namespace std;

inline int read()
{
	int a = 0,f = 1;char ch = getchar();
	while(!isdigit(ch)){if(ch=='-')f=-1;ch=getchar();}
	while(isdigit(ch)){a=a*10+ch-'0';ch=getchar();}
	return a*f;
}

const int N = 4e4+5,inf = 0x7f7f7f7f;
int n,k,tot,rt,cnt,num,MX,ans;
int head[N],sz[N],mx[N],vis[N],dis[N];
struct Edge
{
	int next,to,dis;
}edge[N<<1];
void add_edge(int from,int to,int dis)
{
	edge[++tot] = (Edge){head[from],to,dis};
	head[from] = tot;
}

void get_root(int now,int fath,int total)
{
	sz[now] = 1;mx[now] = 0;
	for(int i = head[now];i;i = edge[i].next)
	{
		int to = edge[i].to;
		if(to == fath || vis[to]) continue;
		get_root(to,now,total);
		sz[now] += sz[to];
		mx[now] = max(mx[now],sz[to]);
	}
	mx[now] = max(mx[now],total-sz[now]);
	if(mx[now] < MX)
		rt = now,MX = mx[rt];
}

void get_dis(int now,int fa,int w)
{
	dis[++cnt] = w;
	for(int i = head[now];i;i = edge[i].next)
	{
		int to = edge[i].to;
		if(vis[to] || to == fa) continue;
		get_dis(to,now,w+edge[i].dis);
	}
}

int Calc(int p,int w)
{
	cnt = 0;
	get_dis(p,0,w);
	sort(dis+1,dis+1+cnt);
	int l = 1,r = cnt,res = 0;
	while(l <= r)
	{
		if(dis[l] + dis[r] <= k) res += r-l,l++;
		else r--;
	}
	return res;
}

void solve(int now)
{
	ans += Calc(now,0);
	vis[now] = 1;
	for(int i = head[now];i;i = edge[i].next)
	{
		int to = edge[i].to;
		if(vis[to]) continue;
		ans -= Calc(to,edge[i].dis);
		rt = 0,MX = inf;
		get_root(to,now,sz[to]);
		solve(rt);
	}
}

int main()
{
	n = read();
	for(int i = 1;i < n;i++)
	{
		int x = read(),y = read(),z = read();
		add_edge(x,y,z);
		add_edge(y,x,z);
	}
	k = read();
	MX = inf,rt = 0;
	get_root(1,0,n);
	solve(rt);
	printf("%d",ans);
	return 0;
}

蒟蒻写得很认真,dalao们不要喷我。

原文