UVALive 5058 Counting BST --组合数

时间:2023-03-08 22:35:56
UVALive 5058 Counting BST --组合数

题意:排序二叉树按照数插入的顺序不同会出现不同的结构,现在要在1~m选n个数,使按顺序插入形成的结构与给出的结构相同,有多少种选法。

解法:先将给出的结构插入,构造出一棵排序二叉树,再dfs统计,首先赋ans = C(m,n),从m个数中取n个数,然后将这n个数安排插入顺序,dfs,如果此时节点左右子树都有,那么其实左右子树的插入顺序可以相间,所有就是一个排列保持相对顺序不变地插入另一个保持相对顺序不变的序列中,有多少种插入方法呢,如果一个序列个数为k1,另一个为k2,那么方法数为:C(k1+k2,k1) = C(k1+k2,k2), 因为总共k1+k2个位置,我们从两个序列中选择k1或k2个位置,那么放入序列只有一种方式,那么其余的k2或k1个就定了。所以dfs求下去即可得出最后答案。

代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <algorithm>
#define SMod 1000003
#define ll long long
using namespace std; int C[][],Node;
int siz[],ch[][],val[];
ll ans; void Insert(int rt,int k) {
if(val[rt] == ) {
val[rt] = k;
siz[rt] = ;
ch[rt][] = ch[rt][] = ;
return;
}
if(k < val[rt]) { //left
if(ch[rt][] == ) ch[rt][] = ++Node;
Insert(ch[rt][],k);
}
else {
if(ch[rt][] == ) ch[rt][] = ++Node;
Insert(ch[rt][],k);
}
siz[rt] = siz[ch[rt][]]+siz[ch[rt][]]+;
return;
} void calc() {
C[][] = ;
for(int i = ; i < ; i++) {
C[i][] = ;
for(int j = ; j <= i; j++)
C[i][j] = (C[i - ][j] + C[i - ][j - ]) % SMod;
}
} void dfs(int u) {
if(ch[u][] && ch[u][]) {
int lsiz = siz[ch[u][]];
int rsiz = siz[ch[u][]];
//cout<<"l,rsiz = "<<lsiz<<" "<<rsiz<<endl;
ans = ans*C[lsiz+rsiz][lsiz]%SMod;
}
if(ch[u][]) dfs(ch[u][]);
if(ch[u][]) dfs(ch[u][]);
} int main()
{
int t,n,m,i,x;
calc();
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&n,&m);
ans = (ll)C[m][n];
memset(val,,sizeof(val));
memset(siz,,sizeof(siz));
memset(ch,,sizeof(ch));
scanf("%d",&val[]);
Node = siz[] = ;
ch[][] = ch[][] = ;
for(i=;i<=n;i++) {
scanf("%d",&x);
Insert(,x);
}
dfs();
cout<<ans<<endl;
}
return ;
}