原题:
Problem Description
Give you two definitions tree and rooted tree. An undirected connected graph without cycles is called a tree. A tree is called rooted if it has a distinguished vertex r called the root. Your task is to make a program to calculate the number of rooted trees with n vertices denoted as Tn. The case n=5 is shown in Fig. 1.
Input
There are multiple cases in this problem and ended by the EOF. In each case, there is only one integer means n(1<=n<=40) .
Output
For each test case, there is only one integer means Tn.
Sample Input
1
2
5Sample Output
1
1
9
对与dfs,记忆化dfs,动态规划,可参考:http://blog.sina.com.cn/s/blog_8eac84090102vt0y.html(讲的很棒)
对于多重集合组合,可参考:http://blog.csdn.net/Ming991301630/article/details/78451710
对于整数拆分,可参考:http://blog.csdn.net/Ming991301630/article/details/78468953
解题思路:
- 此题做法有点类似分治法,对于n个节点有几种不同的树,可看作是根节点有1~n-1个子节点中每个节点的树种类的相加,有点类似与整数拆分:
- 例如:5个节点的树,可能拥有1~4个子节点,即根节点之下一共用4个节点(除了根节点的所有节点肯定在根节点下面:子节点+孙节点+…)。
- 那么4个节点怎么排列呢,就可以看作 4 = 4 = 3+1 = 2+2 = 2+1+1 = 1+1+1+1
- 即:根节点之下,可以只有一个节点(该节点包括子孙节点有4个),或者两个节点(左节点包括子孙节点有3个,右节点包括子孙节点有1个),或者三个节点,或者四个节点。【其他以此类推】
- 所以要求出5个节点有几种树:f(5) = f(4) + f(3)*f(1) + f(2)*C(f(1)+2-1,1) + C(f(1)+4-1,1)
- 之所以用到多重集合的组合数公式C(n+k-1,k),是因为当一个节点之下拥有多个-相同个数子孙节点-的子节点时,如果直接相乘,则会出现重复现象。
使用组合数公式,可以理解为:
- 例如:f(11)有两个子节点,分别是f(5)和f(5),f(5) = 9(即5个节点有9种树),若想要从这9种树中随机选两种(每种树可以选多次),那能够选择的结果种类个数就是C(9 + 2 - 1, 2)。【多重集合的组合数】
- 以下代码从1到40,使用的是dfs求出一个整数的不同种类的拆分数,然后逐个求出各个节点的树的种类。从1到40逐个算,后面的可以直接用前面算好的结果(动态规划)
- 需要注意的是:算n个节点的树的种类,相当于对n-1进行dfs整数拆分,因为根节点不参与运算
代码:
#include<stdio.h>
#include <algorithm>
long long sum[41] = { 0 };
long long temp;
short top, total, now, n;//栈顶指针//dfs函数用于判断总是是否符合要求//要算的数//要算的数减去1(根节点)
short stack[41];//用于保存整数拆分后的结果
long long C(long long n, long long m)//求组合数
{
m = std::min(m, n - m);
long long i, s = 1;
for (i = 1;i <= m;i++)
s = s*(n - i + 1) / i;
return s;
}
void dfs(short index)
{
short i;
short Repnum = 0, Reptime = 1;//重复的数和重复的次数
if (total == n)//满足
{
temp = 1;
for (i = 0; i <= top - 1; i++)
{
if(i != top - 1 && stack[i] == stack[i+1])//i不是最后一个&&这一个与下一个相同
{
Repnum = stack[i];
Reptime++;
if(i + 1 == top - 1)//当下一个就是最后一个的时候
{
temp *= C(sum[Repnum] + Reptime - 1, Reptime);
Reptime = 1;
Repnum = 0;
break;
}
}else if(Repnum != 0)
{
temp *= C(sum[Repnum] + Reptime - 1, Reptime);
Reptime = 1;
Repnum = 0;
}
else
{
temp *= sum[stack[i]];//栈中的数提取出来
}
}
sum[now] += temp;
}
if (total > n)return;
if (total < n)
{
for (i = index; i >= 1; i--)
{
total += i;
stack[top++] = i;
dfs(i);
total -= i;
top--;
}
}
}
int main()
{
short i, a;
sum[1] = sum[2] = 1;
sum[3] = 2; sum[4] = 4;
for (i = 5; i <= 40; i++)
{
top = total = 0;
now = i;
n = i - 1;
dfs(i - 1);
}
while (scanf("%d",&a)!=EOF)
{
printf("%lld\n", sum[a]);
}
}
附加:
//排列组合可直接用的代码:
void A(int n,int m)
{
int i;
for (i = n; i > n - m; i--)
{
sum *= i;
}
}
void C(int n, int m)
{
int i;
m = min(m, n - m);
for (i = 1; i <= m; i++)
{
sum = (sum *(n - i + 1)) / i;
}
}