jzoj5956 【NOIP2018模拟11.7A组】easy LCA (结论)

版权声明:未经作者本人允许禁止转载。 https://blog.csdn.net/jokerwyt/article/details/83827158

在这里插入图片描述

在这里插入图片描述

分析

死因:思路错了
一开始在考虑欧拉序和原序列单调栈的问题,这样想其实可以分治(超麻烦)。

注意到一个结论,假如你要求n个点的lca,那么你可以以任意顺序排序,然后对相邻求lca,再求深度最小的即可。
证明很显然,考虑欧拉序,答案肯定会至少被一组相邻的点盖到,
这样问题就很简单了,做两遍单调栈再枚举答案即可。

其实还有两种做法:将dep转化为个数,这样其实就是查询子树内在给出序列内所有连续段长度的平方和。使用线段树合并(常数较大)或者启发式合并 + 并查集都可以解决。

#include <cstdio>
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 6e5 + 10;
int n;
int final[N],nex[N*2],to[N*2],tot;
char c;
void read(int &x) {
	while ((c=getchar()) < '0' || c > '9'); x=c-'0';
	while (((c=getchar())) >= '0' && c <='9') x = x * 10 + c - '0';
}

void link(int x,int y) {
	to[++tot] = y, nex[tot] = final[x], final[x] = tot;
}

int Q[N],dep[N],g[N][20],fa[N];

int lca(int a,int b) {
	if (dep[a] < dep[b]) swap(a,b);
	for (int i = 19; ~i; i--) if (dep[g[a][i]] >= dep[b])
		a = g[a][i];
	if (a==b) return a;
	for (int i = 19; ~i; i--) if (g[a][i] != g[b][i]) 
		a = g[a][i], b = g[b][i];
	return fa[a];
}

void init() {
	int h = 0, t = 0;
	Q[++t] = 1;
	dep[1] = 1;
	while (h < t) {
		int x = Q[++h];
		for (int i = final[x]; i; i=nex[i]) {
			int y = to[i]; if (y != fa[x]) {
				Q[++t]  = y;
				dep[y] = dep[x] + 1;
				fa[y] = x;
			}
		}
	}
	for (int i = 1; i <= n; i++) g[i][0] = fa[i];
	for (int i = 1; i < 20; i++) {
		for (int j = 1; j <= n; j++) {
			g[j][i] = g[g[j][i - 1]][i - 1];
		}
	}
}

int p[N],w[N],pre[N],S[N],top;
long long ans;

int main() {
	freopen("easy.in","r",stdin);
//	freopen("easy.out","w",stdout);
	cin>>n;
	for (int i = 1; i < n; i++) {
		int u,v; read(u),read(v);
		link(u,v), link(v,u);
	}
	init();
	for (int i = 1; i <= n; i++) scanf("%d",&p[i]);
	for (int i = 1; i < n; i++) {
//		printf("%d %d %d\n",p[i],p[i+1],lca(p[i], p[i + 1]));
		w[i] = dep[lca(p[i], p[i + 1])];
	}
	for (int i = 1; i < n; i++) {
		while (top && w[S[top]] >= w[i]) top--;
		pre[i] = S[top]; S[++top] = i;
	}
	top = 0;
	for (int i = n - 1; i; i--) {
		while (top && w[S[top]] > w[i]) top--;
		long long suf = top ? S[top] : n;
		ans += (suf - i) * (i - pre[i]) * w[i];
		S[++top] = i;
	}
	for (int i = 1; i <= n; i++) ans += dep[i];
	cout<<ans<<endl;
}

猜你喜欢

转载自blog.csdn.net/jokerwyt/article/details/83827158