[模板]笛卡尔树

很好理解,也很好写,只要知道它的两个性质就可以自己yy了
1.堆性质
2.中序遍历序列就是原序列
代码如下:

#include <bits/stdc++.h>

using namespace std;

#define N 100000

int n, a[N+5], fa[N+5], ch[N+5][2];
int stk[N+5], tp;

void build() {
	for(int i = 1; i <= n; ++i) {
		int last = 0;
		while(tp) {
			if(a[stk[tp]] <= a[i]) {
				if(ch[stk[tp]][1]) ch[i][0] = ch[stk[tp]][1], fa[ch[stk[tp]][1]] = i;
				ch[stk[tp]][1] = i, fa[i] = stk[tp];
				break;
			}
			last = stk[tp--];
		}
		if(!tp && last) ch[i][0] = last, fa[last] = i;
		stk[++tp] = i;
	}
}

bool d(int x) {
	return ch[fa[x]][1] == x;
}

int queryLeft(int x) {
	while(fa[x] && d(x) == 0) x = fa[x]; 
	return fa[x];
}

int queryRight(int x) {
	while(fa[x] && d(x) == 1) x = fa[x];
	return fa[x];
}

int main() {
	cin >> n;
	for(int i = 1; i <= n; ++i) cin >> a[i];
	build();
	for(int i = 1; i <= n; ++i)
		printf("%d %d\n", queryLeft(i), queryRight(i));
	return 0;
}
posted @ 2019-01-26 09:29  dummyummy  阅读(320)  评论(0编辑  收藏  举报