Given a 1-N arrangement, insert these numbers into the binary sorting tree in sequence, and ask how many arrangements make the binary tree the same as the given arrangement.
The idea of this question is: first construct the required binary sorting tree, and then conduct DP on the tree
Status transition: DP [RT] = DP [lson] * DP [rson] * C (lson, sum );
Lson indicates the number of points in the left subtree, and sum indicates the sum of the numbers of left and right subtree points.
C (a, B) indicates the number of combinations of a selected in B. Status transfer should be easy to understand.
Code writing is quite frustrating. After all, binary trees are not often written.
# Include <iostream> # include <stdio. h> # include <string. h> using namespace STD; # define mod 9999991 struct note {int Val, L, R, size; long DP;} dat [100]; int KK; void Init () {for (INT I = 0; I <100; I ++) {dat [I]. L = dat [I]. R =-1; dat [I]. val = 0; dat [I]. dp = 1; dat [I]. size = 1 ;}} void insert (int rt, int Val) {If (Val <dat [RT]. val) {If (DAT [RT]. L =-1) {dat [RT]. L = KK; dat [Kk]. val = val; KK ++; return;} el Se insert (DAT [RT]. l, Val);} else {If (DAT [RT]. R =-1) {dat [RT]. R = KK; dat [Kk]. val = val; KK ++; return;} else insert (DAT [RT]. r, Val) ;}} long C [100] [100]; void C () {int I, j; C [0] [0] = 1; for (I = 1; I <40; I ++) // custom for (j = 0; j <= I; j ++) c [I] [J] = (j = 0 )? C [I-1] [J]: C [I-1] [J] + C [I-1] [J-1]; // formula} void DFS (int rt) {If (DAT [RT]. L =-1 & dat [RT]. R =-1) {return;} If (DAT [RT]. l! =-1) DFS (DAT [RT]. L); If (DAT [RT]. R! =-1) DFS (DAT [RT]. R); If (DAT [RT]. l! =-1 & dat [RT]. R! =-1) {dat [RT]. size = dat [dat [RT]. l]. size + dat [dat [RT]. r]. size + 1; int cc = C [dat [RT]. size-1] [dat [dat [RT]. l]. size]; dat [RT]. dp = Cc * dat [dat [RT]. l]. DP * dat [dat [RT]. r]. DP % MOD;} else if (DAT [RT]. L =-1) {dat [RT]. size = dat [dat [RT]. r]. size + 1; dat [RT]. dp = dat [dat [RT]. r]. DP;} else {dat [RT]. size = dat [dat [RT]. l]. size + 1; dat [RT]. dp = dat [dat [RT]. l]. DP ;}} int main () {C (); // cout <C [20] [10]; int t; CIN> T; while (t --) {Init (); int N; CIN> N; int tt; KK = 2; for (INT I = 0; I <n; I ++) {CIN> tt; if (I = 0) DAT [1]. val = tt; else insert (1, TT);} DFS (1); cout <dat [1]. dp <"\ n";} return 0 ;}