Cartesian Tree (Summary of Knowledge + Boardsorting)
Cartesian Tree
Example 1:hdu-6305
RMQ Similar Sequence
[Title]:
IMPORTANT: Defines RMQ(A,l,r) as the minimum I satisfying A[i] = max(A[l],A[l+1],...,A[r]) in sequence A.If any (l,r) satisfies RMQ(A,l,r)=RMQ(B,l,r), then A and B are RMQ Similars.Now that sequence A is shown, each number of sequence B is a real number between 0 and 1. Ask Satisfy the expectation that A is the sum of all numbers in all sequence B of RMQ Similar.
Solution: It is not difficult to see that if A and B are RMQ Similar s, A and B are Cartesian trees isomorphic.Considering that each number in B is a real number between 0 and 1, so the probability of the same number is 0, you can assume that B has different permutations for each number.If the size of each subtree of a Cartesian tree of A is sz[u], then the probability that any B permutation is isomorphic to A isBecause each number in B satisfies a uniform distribution, the expected value is 1/2 and the expected sum is n/2, so the expected sum of all numbers in B that are identical to A is
So: sz[i] refers to the size of each subtree of a Cartesian tree.
Paste code:
hdu-63051 #include<cstdio> 2 #include<algorithm> 3 #include<stack> 4 using namespace std; 5 typedef long long ll; 6 const int N = 1e6 + 5 ; 7 const int INF = 0x3f3f3f3f; 8 const int mod = 1e9+7; 9 inline int read(){ 10 int x = 0 , f = 1 ; 11 char c = getchar(); 12 while ( c < '0' || c > '9' ) { 13 if( c=='-' ) f = -1 ; 14 c = getchar(); 15 } 16 while ( '0' <= c && c <= '9' ){ 17 x = x*10 + c-'0'; 18 c = getchar(); 19 } 20 return x * f ; 21 } 22 typedef struct Node{ 23 int val,fa,sz; 24 int L,R; 25 Node(){} 26 }Node; 27 Node t[N]; 28 stack<int>st; 29 void Init(int n){ 30 for(int i=0;i<=n;i++){ 31 t[i].sz = t[i].L = t[i].R = t[i].fa = 0; 32 } 33 t[0].val = INF; 34 while(!st.empty()) st.pop(); 35 st.push(0); 36 } 37 38 void build(int n){ 39 int k ; 40 for(int i=1;i<=n;i++){ 41 while( !st.empty() && t[st.top()].val < t[i].val ) 42 st.pop(); 43 k = st.top(); 44 t[i].L = t[k].R; 45 t[k].R = i ; 46 t[i].fa = k; 47 t[t[i].L].fa = i ; 48 st.push(i); 49 } 50 } 51 void dfs(int u) { 52 if ( !u ) return ; 53 t[u].sz = 1 ; 54 dfs( t[u].L ); 55 dfs( t[u].R ); 56 t[u].sz += t[t[u].L].sz 57 + t[t[u].R].sz ; 58 } 59 ll inv[N]; 60 void Init() { 61 inv[1] = 1; 62 for (int i = 2; i < N; i++) 63 inv[i] = inv[mod % i] * (mod - mod / i) % mod; 64 } 65 int main() 66 { 67 int T,n; 68 Init(); 69 for ( scanf("%d",&T) ; T ; T-- ){ 70 71 n = read(); 72 Init(n); 73 for(int i=1;i<=n;i++){ 74 t[i].val = read() ; 75 } 76 //puts("####"); 77 78 build(n); 79 dfs(t[0].R); 80 81 ll ans=n *inv[2]%mod; 82 for(int i=1;i<=n;i++) 83 ans=ans*inv[t[i].sz]%mod; 84 85 printf("%lld\n",ans); 86 } 87 return 0; 88 } 89 /* 90 3 91 3 92 1 2 3 93 3 94 1 2 1 95 5 96 1 2 3 2 1 97 */