SP3544 BST - Binary Search Tree
Face questions
answer
Very interesting a question Yeah, hang a written exam
Apparently a number of times equal to the number of insert to add depth to insert his number
Depending on the nature of BST
When we inserted a number of functions that operate according to his Insert
For this he must have the right number of his predecessor's son also left some of his subsequent sons (no duplicate numbers and 1-N)
Because of his insertion does not guarantee a balance, obviously inserted certain number of predecessor and successor in the next layer
And a deeper depth in the next layer
(My feeling proved wrong)
So we just need to focus on his predecessor and successor on the line
A set directly on the line
Can also be optimized
Consider [NOI2004] depressed teller routine
When we focus only on precursors and successors can use the list to achieve a linear approach
Since the end of the state and will only lead to delete certain number of two effects can be O (1) is calculated
Consider the list maintenance treatment with reverse current sequence pointed to his predecessor and successor
code show as below
#include<bits/stdc++.h> using namespace std; const int MAXN = 300000 + 10; inline int read() { int f=1,x=0; char ch; do { ch=getchar(); if(ch=='-') f=-1; }while(ch<'0'||ch>'9'); do { x=(x<<3)+(x<<1)+ch-'0'; ch=getchar(); }while(ch>='0'&&ch<='9'); return f*x; } int n; int a[MAXN]; int l[MAXN],r[MAXN],pre[MAXN],nex[MAXN]; long long dep[MAXN],ans; int main() { n=read(); for(int i=1;i<=n;i++) a[i]=read(); for(int i=1;i<=n;i++) { l[i]=i-1;r[i]=i+1; } l[1]=0;r[n]=0; cout<<0<<endl; for(int i=n;i>=1;i--) { pre[a[i]]=l[a[i]]; nex[a[i]]=r[a[i]]; r[l[a[i]]]=r[a[i]]; l[r[a[i]]]=l[a[i]]; } for(int i=2;i<=n;i++) { dep[a[i]]=max(dep[pre[a[i]]],dep[nex[a[i]]])+1; ans+=dep[a[i]]; cout<<ans<<endl; } }