首页 > 其他 > 详细

Red-black Tree

时间:2020-02-09 09:16:32      阅读:81      评论:0      收藏:0      [点我收藏+]

There is a kind of binary tree named red-black tree in the data structure. It has the following 5 properties:

  • (1) Every node is either red or black.
  • (2) The root is black.
  • (3) All the leaves are NULL nodes and are colored black.
  • (4) Each red node must have 2 black descends (may be NULL).
  • (5) All simple paths from any node x to a descendant leaf have the same number of black nodes.

We call a non-NULL node an internal node. From property (5) we can define the black-height of a red-black tree as the number of nodes on the simple path from the root (excluding the root itself) to any NULL leaf (including the NULL leaf). And we can derive that a red-black tree with black height H has at least 2?H??1 internal nodes.

Here comes the question: given a positive N, how many distinct red-black trees are there that consist of exactly N internal nodes?

Input Specification:

Each input file contains one test case which gives a positive integer N (≤).

Output Specification:

For each case, print in a line the number of distinct red-black tees with N internal nodes. Since the answer may be very large, output the remainder of it divided by 1000000007 please.

Sample Input:

5
 

Sample Output:

8
 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 vector<long long> vr;
 4 vector<long long> vb;
 5 #define mod 1000000007
 6 int main()
 7 {
 8 //      freopen("data.txt","r",stdin);
 9       int n;
10       scanf("%d",&n);
11       int m=min(n,10);
12       vr.resize(n*m,0);
13        vb.resize(n*m,0);
14        if(n)
15        {
16         vb[0]=1;
17         vb[1]=2;
18         vb[2]=1;
19     }
20       for(int i=1;i<m;i++)
21       {
22         for(int j=2;j<n;j++)
23         {
24             for(int k=0;k<j-1;k++)
25             {
26                 long long s1=(vb[(i-1)*n+k]+vr[(i-1)*n+k])%mod;
27                 long long s2=(vb[(i-1)*n+j-k-2]+vr[(i-1)*n+j-k-2])%mod;
28                 vb[i*n+j]+=(s1*s2)%mod;
29                 vb[i*n+j]%=mod;
30                 vr[(i-1)*n+j]+=((vb[(i-1)*n+k]%mod)*(vb[(i-1)*n+j-2-k]%mod));
31                 vr[(i-1)*n+j]%=mod;
32             }
33         }
34     }
35     long long s=0;
36     for(int i=0;i<m;i++)
37     (s+=vb[i*n+n-1])%=mod;
38     printf("%lld",s);
39     return 0;
40 }

 

Red-black Tree

原文:https://www.cnblogs.com/SkystarX/p/12285808.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!