2022-04-04 集訓題解
阿新 • • 發佈:2022-04-04
T2
Description
小 W 的手上有一顆 \(n\) 個節點的二叉搜尋樹,裡面有從 \(1\) 到 \(n\) 這 \(n\) 個數字。(二叉搜尋樹即為中序遍歷恰好為 \(1\) 到 \(n\) 的二叉樹)
現在你想知道這棵樹的形態。但是小 W 不會直接告訴你,只允許你詢問以某個點為根的子樹是否恰好包含 \([l,r]\) 中的所有點。
你需要在 \(2\times n\) 次查詢之內得到整棵樹的形態。
Solution
考慮建立笛卡爾樹的步驟,那我們需要做的就是一個點是否在另外一個點的左兒子裡面,你發現既然已經當了左兒子,那麼裡面一定已經構造完了,所以我們只需要判斷這個點是否覆蓋這個區間即可。
Code
#include<bits/stdc++.h> #include"interact.h" using namespace std; #define Int register int #define MAXN 105 struct node{ int x,l; }; node sta[MAXN]; int lson[MAXN],rson[MAXN]; int getr (int x){ while (rson[x]) x = rson[x]; return x; } void guess(int n){ int top = 0; for (Int i = 1;i <= n;++ i){ int l = i; while (top && query (sta[top].x,sta[top].l,getr (sta[top].x))) lson[i] = sta[top].x,l = sta[top].l,-- top; if (top) rson[sta[top].x] = i; sta[++ top] = node{i,l}; } for (Int i = 1;i <= n;++ i){ if (lson[i]) report (i,lson[i]); if (rson[i]) report (i,rson[i]); } }