跳到正文

算法·理论

模板代码——笛卡尔树

wbqhasvcf约 2 分钟
原文
文章信息与版本

文章信息

发布
2026年10月19日
收录
2026年11月26日
更新
2026年11月26日
篇幅
约 2 分钟

版本

  1. v1当前
C++
//构建数组下标满足二叉搜索树性质,下标对应的值满足小根堆性质的笛卡尔树 
#include<bits/stdc++.h>
#define ll long long
#define rep(i,x,y) for(int i=x;i<=y;i++)
using namespace std;
const int N=1e7+5;

int n,a[N];
ll l[N],r[N],ansl,ansr;
stack<int> sk;
inline int read()
{
	int ret=0,fh=1;
	char ch=getchar();
	for(;!isdigit(ch);ch=getchar())
		if(ch=='-') fh=-1;
	for(;isdigit(ch);ch=getchar())
		ret=ret*10+ch-'0';
	return ret;
}
int main()
{
	n=read();
	rep(i,1,n) a[i]=read();
	sk.push(1); 
	rep(i,2,n)
	{
		int tp=0;
		//利用栈来维护树的右链,不在右链上的点出栈,这样每个点最多进出栈一次,可保证笛卡尔树建树的时间复杂度为O(n) 
		while(!sk.empty()&&a[i]<a[sk.top()])
			tp=sk.top(),sk.pop();
		//如果当前元素大于等于堆顶元素,说明当前元素存在父节点(即当前栈顶元素)且为其右儿子 
		if(!sk.empty()) r[sk.top()]=i; 
		//如果父节点存在右子树,就将右子树的根节点(即上一个栈顶元素tp)作为当前节点的左儿子 
		if(tp!=0) l[i]=tp;
		sk.push(i);
	}
	rep(i,1,n) ansl^=i*(l[i]+1),ansr^=i*(r[i]+1);
	cout<<ansl<<" "<<ansr;
	return 0;
}
原文