luogu P2633 Count on a tree

背景:

今天快船又双战胜了勇士, Durant \text{Durant} Durant空砍 45 pts 45\text{pts} 45pts Louis Williams NB \text{Louis\ Williams}\ \text{NB} Louis Williams NB

题目传送门:

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

题意:

一棵树,在线询问 x − y x-y xy路径上的第 k k k小值。

思路:

就是用主席树维护一棵树。
具体来说,对于每一个点,就是你维护一棵主席树从当前点到根的值。
你考虑树上差分。
a n s x , y = a n s 1 , x + a n s 1 , y − a n s 1 , l c a x , y − a n s 1 , fa lca x , y ans_{x,y}=ans_{1,x}+ans_{1,y}-ans_{\text1,{lca}{x,y}}-ans_{1,\text{fa}_{\text{lca}{x,y}}} ansx,y=ans1,x+ans1,yans1,lcax,yans1,falcax,y
对于 lca \text{lca} lca你用倍增不就可以可以了吗。
INF \text{INF} INF的初始化错了,调了我一天。
over. \text{over.} over.

代码:

#include<cstdio>
#include<cstring>
#include<algorithm>
#define INF (2147483647)
#define LL long long
using namespace std;
	struct node{int x,y,next;} a[200010];
	int last[200010],f[200010][20],dep[200010];
	int ls[8000010],rs[8000010],root[200010],tot[8000010],d[200010];
	int n,m,len=0;
void ins(int x,int y)
{
	a[++len]=(node){x,y,last[x]}; 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;
		f[y][0]=x;
		dep[y]=dep[x]+1;
		dfs1(y);
	}
}
void init()
{
	for(int i=1;i<=18;i++)
		for(int j=1;j<=n;j++)
			f[j][i]=f[f[j][i-1]][i-1];
}
int lca(int x,int y)
{
	if(dep[x]<dep[y]) swap(x,y);
	for(int i=18;i>=0;i--)
		if(dep[f[x][i]]>=dep[y]) x=f[x][i];
	if(x==y) return x;
	for(int i=18;i>=0;i--)
		if(f[x][i]!=f[y][i]) x=f[x][i],y=f[y][i];
	return f[x][0];
}
void change(int last,int &now,int x,int l,int r)
{
	if(!now) now=++len;
	tot[now]=tot[last]+1;
	if(l==r) return;
	int mid=((LL)l+r)/2ll;
	if(x<=mid)
	{
		rs[now]=rs[last];
		change(ls[last],ls[now],x,l,mid);
	}
	else
	{
		ls[now]=ls[last];
		change(rs[last],rs[now],x,mid+1,r);
	}
}
void dfs2(int x)
{
	change(root[f[x][0]],root[x],d[x],-INF,INF);
	for(int i=last[x];i;i=a[i].next)
	{
		int y=a[i].y;
		if(y==f[x][0]) continue;
		dfs2(y);
	}
}
int solve(int x,int y,int u,int v,int k,int l,int r)
{
	if(l==r) return l;
	int tmp=tot[ls[x]]+tot[ls[y]]-tot[ls[u]]-tot[ls[v]],mid=((LL)l+r)/2ll;
	return k<=tmp?solve(ls[x],ls[y],ls[u],ls[v],k,l,mid):solve(rs[x],rs[y],rs[u],rs[v],k-tmp,mid+1,r);
}
int work(int x,int y,int k)
{
	int LCA=lca(x,y);
	return solve(root[x],root[y],root[LCA],root[f[LCA][0]],k,-INF,INF);
}
int main()
{
	int x,y,k,lastans=0;
	scanf("%d %d",&n,&m);
	for(int i=1;i<=n;i++)
		scanf("%d",&d[i]);
	for(int i=1;i<n;i++)
	{
		scanf("%d %d",&x,&y);
		ins(x,y),ins(y,x);
	}
	dep[1]=1;
	dfs1(1);
	init();
	len=0;
	dfs2(1);
	for(int i=1;i<=m;i++)
	{
		scanf("%d %d %d",&x,&y,&k);
		x^=lastans;
		printf("%d\n",lastans=work(x,y,k));
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值