JZOJ5956. 【NOIP2018模拟11.7A组】easy LCA

在这里插入图片描述
在这里插入图片描述

题解

可以知道连续一段的lca是他们两两lca中深度最小的一个。
这样就可以先预处理出来两两的lca的一个序列,这个序列的长度是n-1的。
通过前面的结论,考虑一个lca的贡献,
显然是左边连续的一段深度比它大与右边连续一段深度比它大的。
换句话说就是找左边第一个比它小的,右边第一个比它小的。
单调栈。

code

#include<cstdio>
#include<cstring>
#include<algorithm>
#define ll long long
using namespace std;
const int N=600003;
int n,p[N],x,y,tot,nxt[N*2],to[N*2],lst[N];
int dep[N],f[20][N],now,t,d[N],g[N];
int z[N],top,v[N],w[N];
ll ans;
char ch;
void read(int&n)
{
	for(ch=getchar();ch<'0' || ch>'9';ch=getchar());
	for(n=0;'0'<=ch && ch<='9';ch=getchar())n=(n<<1)+(n<<3)+ch-48;
}
void ins(int x,int y)
{
	nxt[++tot]=lst[x];
	to[tot]=y;
	lst[x]=tot;
}
void bfs()
{
	int l=0,r=1,x;
	for(d[1]=1;l<r;)
	{
		x=d[++l];
		dep[x]=dep[f[0][x]]+1;
		for(int i=lst[x];i;i=nxt[i])
			if(to[i]^f[0][x])f[0][to[i]]=x,d[++r]=to[i];
	}
}
int lca(int x,int y)
{
	if(dep[x]<dep[y])swap(x,y);
	for(int i=19;i+1;i--)
		if(dep[f[i][x]]>=dep[y])x=f[i][x];
	if(x==y)return x;
	for(int i=19;i+1;i--)
		if(f[i][x]^f[i][y])x=f[i][x],y=f[i][y];
	return f[0][x];
}
int main()
{
	freopen("easy.in","r",stdin);
	freopen("easy.out","w",stdout);
	read(n);
	for(int i=1;i<n;i++)
		read(x),read(y),ins(x,y),ins(y,x);
	bfs();
	for(int i=1;i<=n;i++)read(p[i]),ans=ans+dep[i];
	for(int j=1;j<20;j++)
		for(int i=1;i<=n;i++)
			f[j][i]=f[j-1][f[j-1][i]];
	for(int i=1;i<n;i++)g[i]=dep[lca(p[i+1],p[i])];
	z[top=1]=0;
	for(int i=1;i<n;i++)
	{
		for(;top && g[z[top]]>=g[i];top--);
		v[i]=i-z[top];z[++top]=i;
	}
	z[top=1]=n;
	for(int i=n-1;i;i--)
	{
		for(;top && g[z[top]]>g[i];top--);
		w[i]=z[top]-i;z[++top]=i;
	}
	for(int i=1;i<n;i++)ans=ans+(ll)g[i]*w[i]*v[i];
	printf("%lld\n",ans);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值