luogu P3066 [USACO12DEC]逃跑的BarnRunning Away From…

背景:

Lillard \text{Lillard} 超远三分绝杀雷霆,并且砍下 50 pts 50\text{pts}
Lillard   NB \text{Lillard\ \ \ NB}

题目传送门:

https://www.luogu.org/problemnew/show/P3066

题意:

一棵树,询问以每一个点为根的子树中小于等于 m m 的有多少个。

思路:

树上差分。
倍增找出第一个与 x x 距离小于等于 m m 的点 t t ,在当前 x x 这个点 + 1 +1 ,在 t t 这个点的父亲 1 -1 即可。
树上查分标准套路。
常数小,代码短。

代码:

#include<cstdio>
#include<cstring>
#include<algorithm>
#define LL long long
using namespace std;
	struct node{int x,y,next;LL z;} a[400010];
	int n,len=0;
	LL m;
	int last[200010],f[200010][20],ans[200010];
	LL dis[200010];
void ins(int x,int y,LL z)
{
	a[++len]=(node){x,y,last[x],z}; last[x]=len;
}
void dfs1(int x)
{
	for(int i=last[x];i;i=a[i].next)
	{
		int y=a[i].y;
		if(y==f[x][0]) continue;
		dis[y]=dis[x]+a[i].z;
		f[y][0]=x;
		dfs1(y);
	}
}
void init()
{
	for(int j=1;j<=n;j++)
		for(int i=1;i<=18;i++)
			f[j][i]=f[f[j][i-1]][i-1];
}
void dfs2(int x)
{
	for(int i=last[x];i;i=a[i].next)
	{
		int y=a[i].y;
		if(y==f[x][0]) continue;
		dfs2(y);
		ans[x]+=ans[y];
	}
}
int main()
{
	int x;
	LL z;
	scanf("%d %lld",&n,&m);
	for(int i=2;i<=n;i++)
	{
		scanf("%d %lld",&x,&z);
		ins(i,x,z),ins(x,i,z);
	}
	dfs1(1);
	init();
	for(int i=1;i<=n;i++)	
	{
		int t=i;
		for(int j=18;j>=0;j--)
			if(dis[i]-dis[f[t][j]]<=m) t=f[t][j];
		ans[i]++;
		ans[f[t][0]]--;
	}
	dfs2(1);
	for(int i=1;i<=n;i++)
		printf("%d\n",ans[i]);
}

猜你喜欢

转载自blog.csdn.net/zsyz_ZZY/article/details/89496245