Ultraviolet A 1264-Binary Search Tree
Question Link
Given a sequence, insert a binary sorting tree and ask how many of them are the same as the original sequence (including the original sequence)
Idea: Build a tree first, and then run DFS again. For a subtree, you only need to ensure the order on the left and right. Therefore, the number is C (total number of left and right nodes, and left node ), then multiply the left and right subtree according to the multiplication principle.
Code:
# Include <cstdio> # include <cstring> typedef long ll; const int maxnode = 1111111; const int n = 21; const int mod = 9999991; int C [N] [N]; struct BST {struct node {int L, R, Val, lsz, rsz; node () {L = 0, r = 0, val =-1; lsz = 0; rsz = 0 ;}} node [maxnode]; int SZ; void Init () {node [1] = node (); SZ = 2;} void insert (int x, int v) {If (node [X]. val =-1) {node [X]. val = V; return;} If (v <node [X]. val) {If (! Node [X]. l) {node [SZ] = node (); node [X]. L = SZ ++;} insert (node [X]. l, V); node [X]. lsz ++;} else {If (! Node [X]. r) {node [SZ] = node (); node [X]. R = SZ ++;} insert (node [X]. r, V); node [X]. rsz ++ ;}} int DFS (int x) {If (x = 0) return 1; Return (LL) DFS (node [X]. l) * DFS (node [X]. r) % mod * C [node [X]. lsz + node [X]. rsz] [node [X]. lsz] % MOD;} void solve () {Init (); int N, num; scanf ("% d", & N); While (n --) {scanf ("% d", & num); insert (1, num) ;}printf ("% d \ n", DFS (1) ;}} Gao; int t; void GETC () {for (INT I = 0; I <n; I ++) {c [I] [0] = C [I] [I] = 1; for (Int J = 1; j <I; j ++) c [I] [J] = C [I-1] [J-1] + C [I-1] [J] ;}} int main () {GETC (); scanf ("% d", & T); While (t --) {Gao. solve ();} return 0 ;}
1264-Binary Search Tree (BST + count)