cunzai_zsy0531

关注我

P1377 [TJOI2011]树的序 题解

题面

这个题相当于是把每个数的值作为 \(x_i\),在原序列中的位置为 \(y_i\),建出笛卡尔树,直接输出先序遍历(字典序最小)即可。

点击查看代码
#include<iostream>
#include<cstdio>
using namespace std;
inline int rd(){
	int res=0;char c=getchar();
	for(;!isdigit(c);c=getchar());
	for(;isdigit(c);c=getchar())res=(res<<1)+(res<<3)+(c-'0');
	return res;
}
const int N=1e5+13;
int n,a[N],s[N],top,L[N],R[N];
void dfs(int u){
	printf("%d ",u);
	if(L[u]) dfs(L[u]);
	if(R[u]) dfs(R[u]);
}
int main(){
	n=rd();int rt=0;
	for(int i=1,x;i<=n;++i) x=rd(),a[x]=i;
	for(int i=1;i<=n;++i){
		int pos=top;
		while(pos&&a[s[pos]]>a[i]) --pos;
		if(pos) R[s[pos]]=i;
		if(pos<top) L[i]=s[pos+1];
		s[top=(++pos)]=i;
	}
	dfs(s[1]);
	return 0;
}
posted @ 2022-05-19 16:13  cunzai_zsy0531  阅读(17)  评论(0编辑  收藏  举报