题目分析
泡泡的编号依次插入,显然构成小根堆,又因为泡泡的大小构成二叉搜索树,发现是笛卡尔树。
核心思路
以泡泡的大小与编号作为权值构建笛卡尔树,然后直接后序遍历。
代码实现
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;
}
}