标签:
Description
Binary Search Tree (BST) is a rooted binary tree data structure which has following properties:
If there is a new node to be inserted, the following algorithm will be used:
BST structure depends on its data inserting sequence. Different sequence may yield a different structure though the data set is the same. For example:
Insert sequence: 1 2 3, the BST will be:
If the data is inserted with sequence: 2 1 3, the tree will be:
On the other hand, different data set may have a same BST structure.
For example: Insert sequence 2 1 3 will have the same BST structure with 4 6 2, and the tree will be:
Given N nodes BST, calculate how many distinct insert data sequence which result in the same BST structure, assuming that data are taken from range 1..M.
Input
The first line of input contains an integer T(T100), the number of test cases. Each case begins with two integers N and M(1NM1, 000), the number of nodes in BST and the maximum range respectively. The next line contains N integers Ai(1Ai1, 000) the insert sequence that construct a BST.
Output
For each case, output an integer denoting the number of distinct insert data sequence which result in the same BST structure, assuming that data are taken from range 1..M. ç Modulo this number with 1,000,003.
Note: Explanation for the 1st sample input.
There are 8 insert sequences (data taken from 1..4) which have the same BST:
Sample Input
3 3 4 3 1 4 3 5 1 2 3 4 4 2 1 10 3
Sample Output
8 10 3
#include<bits/stdc++.h> #define eps 1e-9 #define FOR(i,j,k) for(int i=j;i<=k;i++) #define MAXN 1005 #define MAXM 40005 #define MOD 1000003 #define INF 0x3fffffff using namespace std; typedef long long LL; LL i,j,k,n,m,x,y,T,ans,big,cas,w,t,u,v; bool flag; LL a[2010],num[2010]; LL yh[2010][2010]; void BuildYangHui(LL n) { LL i,j; yh[0][0]=1;yh[0][1]=0; for (i=1;i<=n;i++) { yh[i][0]=1; for (j=1;j<=n;j++) { yh[i][j]=(yh[i-1][j-1]+yh[i-1][j])%MOD; } } } LL lc[2010],rc[2010]; void BuildBST(LL n) { LL cur=1; for (LL i=2;i<=n;i++) { cur=1; while (1) { if (a[i]<a[cur]) { if (!lc[cur]) { lc[cur]=i; break; }else cur=lc[cur]; }else { if (!rc[cur]) { rc[cur]=i; break; }else cur=rc[cur]; } } } } LL CalcNodes(LL u)//以u为根的子树的节点数 { if (u==0) return 0; if (num[u]!=0) return num[u]; return num[u]=CalcNodes(lc[u])+CalcNodes(rc[u])+1; } LL FUNC(LL u) { if (u==0) return 1; return yh[ num[lc[u]]+num[rc[u]] ][ num[rc[u]] ]* FUNC(lc[u]) % MOD *FUNC(rc[u]) %MOD; } int main() { scanf("%lld",&T); BuildYangHui(2002); while (T--) { scanf("%lld%lld",&n,&m); for (i=1;i<=n;i++) { scanf("%lld",&a[i]); } memset(num,0,sizeof(num)); memset(lc,0,sizeof(lc)); memset(rc,0,sizeof(rc)); BuildBST(n);//构造BST树 CalcNodes(1);//计算结点数 printf("%lld\n",FUNC(1)*yh[m][n]%MOD); } return 0; }
标签:
原文地址:http://www.cnblogs.com/qscqesze/p/4231513.html