跳到正文

题解

题解:P10421 [蓝桥杯 2023 国 A] 树上的路径

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

文章信息

发布
2025年6月22日
收录
2025年12月12日
更新
2026年11月3日
篇幅
约 6 分钟
获赞
1
题目
P10421

版本

  1. v1当前

前言

冲中考停了两个月竞赛,康复训练题目,所以写得比较史也是成功收获最劣解,但是思路还是没问题的。

思路

首先我们发现这是一颗树还是求树上关于路径的问题,直接考虑点分治(不会的话去学一下吧),我们发现我们对于点分治遍历到一条长度为 xx 的路径那么另一条路径的长度需要在 l−x∼r−xl-x\sim r-x 之间所以我们需要一个支持单点修改区间求和的数据结构,直接上树状数组即可。

时间复杂度 O(n×log⁡2(n))O(n\times \log^2(n))。

代码

细节见代码。

C++
#include <bits/stdc++.h>
#include<ext/pb_ds/assoc_container.hpp>
#include<ext/pb_ds/tree_policy.hpp>
#include <ext/rope>
using namespace __gnu_pbds;
using namespace std;
#define pb push_back
#define rep(i,x,y) for(register int i=x;i<=y;i++)
#define rep1(i,x,y) for(register int i=x;i>=y;--i)
#define ll long long
#define fire signed
#define il inline
template<class T> il void print(T x) {
	if(x<0) printf("-"),x=-x;
	if (x > 9) print(x / 10);
	putchar(x % 10 + '0');
}
template<class T> il void in(T &x) {
    x = 0; char ch = getchar();
    int f = 1;
    while (ch < '0' || ch > '9') {if(ch=='-') f = -1; ch = getchar(); }
    while (ch >= '0' && ch <= '9') { x = (x << 3) + (x << 1) + (ch ^ 48); ch = getchar(); }
    x *= f;
}
int T=1;
const int N=2e6+10;
ll tr[N];
int cnt[N];
vector<int>v[N];
int n;
int l,r,mx[N],rt,sum;
int lowbit(int x) {
	return x&-x;
}
void add(int x,int k) {
	x++;
	for(;x<=n+1;x+=lowbit(x)) tr[x]+=1ll*k,cnt[x]++;
}
ll Ans(int x){
	if(x<0) return false;
	x++;
	ll res=0;
	for(;x;x-=lowbit(x)) res+=tr[x];
	return res;
}
int Ans1(int x) {
	if(x<0) return false;
	x++;
	int res=0;
	for(;x;x-=lowbit(x)) res+=cnt[x];
	return res;
}
int vis[N],siz[N];
void frt(int x,int fa) {
	siz[x]=1;
	mx[x]=1;
	for(auto to:v[x]) {
		if(to==fa||vis[to]) continue;
		frt(to,x);
		mx[x]=max(mx[x],siz[to]);
		siz[x]+=siz[to];
	}
	mx[x]=max(mx[x],sum-siz[x]);
	if(mx[x]<mx[rt]) rt=x;
}
void clear(int x) {
	x++;
	for(;x<=n+1;x+=lowbit(x)) tr[x]=cnt[x]=false;
}
int dis[N];
vector<int>arr;
void dfs1(int x,int fa) {
	arr.pb(dis[x]);
	for(auto to:v[x]) {
		if(to==fa||vis[to]) continue;
		dis[to]=dis[x]+1;
		dfs1(to,x);
	}
}
ll res;
void dfs2(int x,int fa) {
	siz[x]=1;
	for(auto to:v[x]) {
		if(to==fa||vis[to]) continue;
		dfs2(to,x);
		siz[x]+=siz[to];
	}
}
void dfs(int x,int fa) {
	vis[x]=1;
	vector<int>ad;
	ad.pb(0);
	add(0,0);
	for(auto to:v[x]) {
		if(to==fa||vis[to]) continue;
		arr.clear();
		dis[to]=1;
		dfs1(to,x);
		for(auto to1:arr) {
			if(r-to1<0) continue;
			int cc=Ans1(r-to1)-Ans1(l-to1-1);
			res+=1ll*cc*to1;
			res+=Ans(r-to1)-Ans(l-to1-1);
		}
		for(auto to1:arr) {
			if(to1>r) continue;
			ad.pb(to1);
			add(to1,to1);
		}
	}
	for(auto to:ad) clear(to);
	dfs2(x,0);
	for(auto to:v[x]) {
		if(to==fa||vis[to]) continue;
		rt=false;
		sum=siz[to];
		frt(to,x);
		dfs(rt,x);
	}
}
void solve() {
	in(n),in(l),in(r);
	rep(i,2,n) {
		int x;
		in(x);
		v[x].pb(i);
		v[i].pb(x);
	}
	rt=0;
	sum=n;
	mx[rt]=1e9;
	frt(1,0);
	dfs(rt,0);
	printf("%lld\n",res);
}
fire main() {
	while(T--) {
		solve();
	}
	return false;
}
原文