跳到正文

题解

题解:P2171 Hz 吐泡泡

Lin20120423约 4 分钟
原文
文章信息与版本

文章信息

发布
2025年10月12日
收录
2026年7月16日
更新
2026年11月3日
篇幅
约 4 分钟
题目
P2171

版本

  1. v1当前

蒟蒻的第一篇题解

题目传送门

这道题其实是模板题加上查树的深度及后序输出

不知道怎么讲解,那就直接看Code吧,里面有注释

C++
#include<bits/stdc++.h>
#define int long long
using namespace std;
struct Node{
	int key,value;
	Node* parent;
	Node* left;
	Node* right;
	Node(int _key,int _value):key(_key),value(_value),parent(nullptr),left(nullptr),right(nullptr){}
	//初始化
};
class CartesianTree{
private:
	int n;
	Node* root;
	vector<Node*> nodes;
	static bool cmp(Node* a,Node* b){//按键值大小排序
		return a->key<b->key;
	}
public:
	CartesianTree(const vector<int>& _keys,const vector<int>& _values){//建树
		n=_keys.size();
		nodes.resize(n);
		for(int i=0;i<n;i++)
			nodes[i]=new Node(_keys[i],_values[i]);
		sort(nodes.begin(),nodes.end(),[](Node* a, Node* b){return a->key<b->key;});
		build();
	}
	void build(){
		stack<Node*> _stack;
		for(int i=0;i<n;i++){
			Node* last=nullptr;
			while(!_stack.empty()&&_stack.top()->value>nodes[i]->value){
				last=_stack.top();//找栈中第一个比当前节点value低的节点
				_stack.pop();
			}
			if(!_stack.empty()){//栈不为空则把当前节点加到栈顶节点的右子树上
				_stack.top()->right=nodes[i];
				nodes[i]->parent=_stack.top();
			}else{//栈为空则当前节点为根节点
				root=nodes[i];
			}
			if(last!=nullptr){//弹出栈后如果有节点则加入到当前节点左子树
				nodes[i]->left=last;
				last->parent=nodes[i];
			}
			_stack.push(nodes[i]);
		}
	}
	int Depth(Node* node){//求树的深度
		if(node==nullptr)return 0; 
		return max(Depth(node->left),Depth(node->right))+1;
	}
	void dfs(Node* node){//dfs后序输出
        if(node==nullptr)return ;
        dfs(node->left);
        dfs(node->right);
        cout<<node->key<<'\n';
    }
	void print(){//输出
		cout<<"deep="<<Depth(root)<<'\n';
		dfs(root);
	}
};
void solve(){
	int n;cin>>n;
	vector<int> a(n),b(n);
	for (int i=0;i<n;i++){
		cin>>a[i];//输入键值
		b[i]=i+1;//手输优先级
	}
	CartesianTree CT(a,b);//传入键值和优先级建树
	CT.print();//输出
}
signed main(){
	ios::sync_with_stdio(0);
	cin.tie(0);cout.tie(0);//不加速会TLE
	solve();
	return 0;
}

手残写了一个小时希望大家喜欢

蒟蒻的思路,如有错误还请各位大佬指点^_^

原文