跳到正文

题解

题解:P2171 Hz 吐泡泡

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

文章信息

发布
2026年3月11日
收录
2026年3月14日
更新
2026年11月15日
篇幅
约 2 分钟
获赞
2
题目
P2171

版本

  1. v2当前
  2. v1

题目分析

泡泡的编号依次插入,显然构成小根堆,又因为泡泡的大小构成二叉搜索树,发现是笛卡尔树。

核心思路

以泡泡的大小与编号作为权值构建笛卡尔树,然后直接后序遍历。

代码实现

C++
namespace Sci {
	const int N = 1e7;
	int n;
	struct node {
		int i, v;
		bool operator<(node _) {
			return v < _.v;
		}
	} a[N];
	int rt;
	int ls[N], rs[N];
	vector<int> ans;
	int deep;
	void build() {
		stack<int> _;
		for(int i = 1; i <= n; i++) {
			int t = -1;
			while(_.size() && a[i].i < a[_.top()].i) {
				t = _.top();
				_.pop();
			}
			if(_.size()) rs[_.top()] = i;
			if(t != -1) ls[i] = t;
			_.push(i);
		}
		while(_.size()) {
			rt = _.top();
			_.pop();
		}
	}
	void dfs(int u, int dep) {
		if(u == 0) return;
		dfs(ls[u], dep + 1);
		dfs(rs[u], dep + 1);
		deep = max(deep, dep);
		ans.push_back(u);
	}
	void qud() {
		cin >> n;
		for(int i = 1; i <= n; i++)
			cin >> a[i].v, a[i].i = i;
		sort(a + 1, a + n + 1);
		build();
		dfs(rt, 1);
		cout << "deep=" << deep << endl;
		for(auto i : ans)
			cout << a[i].v << endl;
	}
}
原文