Counting Binary Trees
Time Limit: 6000/3000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 485 Accepted Submission(s): 146
Problem Description
There are 5 distinct binary trees of 3 nodes:
Let T(n) be the number of distinct non-empty binary trees of no more than
n nodes, your task is to calculate T(n) mod
m.
Input
The input contains at most 10 test cases. Each case contains two integers n and m (1 <= n <= 100,000, 1 <= m <= 10
9) on a single line. The input ends with n = m = 0.
Output
For each test case, print T(n) mod m.
Sample Input
Sample Output
题目大意:
题目意思很好懂,只不过难得找规律。大概两个月之前看过这个题,当时雄鹰说是把规律找出来了,不过他老是WA。想的太简单了。
解题思路:看了题解之后,是卡特兰数的问题。h(n)=h(n-1)*(4*n-2)/(n+1) 把前n项求和取余。不过如果直接算每一步,然后mod m的话,有错误,因为h(i-1)%m后,h(i-1)*(4*i-2)不一定能整除(i+1),所以不行。需要把答案看做两部分的乘积:一部分是与m互素的,这一部分的乘法直接计算,除法改成乘逆元就行了。然后就是需要把m因子给分解了,然后找互质的。这道题目在11月6号又思索了一遍,思路很清晰了,先将m因子分解,然后再每一步对分子分母依次分解,如果可以分母与分子存在公共的因子,就num[i]--,剩下的就容易理解了,分子直接乘然后取模,分母乘以逆元然后取模即可。
题目地址:Counting Binary Trees
AC代码:
#include<iostream>
#include<cstring>
#include<string>
#include<cstdio>
#include<cmath>
using namespace std;
int prim[10005],p;
//prim用来保存PHI的值
int num[10005];
int n,m;
void extend_gcd(int a,int b,int &x,int &y)
{
if(b==0)
{
x=1;
y=0;
}
else
{
int t;
extend_gcd(b,a%b,x,y);
t=x; x=y;
y=t-(a/b)*y;
}
}
void cal1(__int64 &ans,int x) //计算(4*n-2)
{
int i;
//先把与因子不互质的找出来
for(i=0;i<p;i++)
{
while(x%prim[i]==0)
{
x/=prim[i];
num[i]++;
}
}
//与m因子互质的,直接求
ans=(ans*x)%m;
}
void cal2(__int64 &ans,int q) //计算(n+1)
{
int i;
//先把与因子不互质的找出来
for(i=0;i<p;i++)
{
while(q%prim[i]==0&&num[i]>0)
{
num[i]--;
q/=prim[i];
}
}
//与因子不互质的需要用扩展欧拉来求逆元
if(q>1)
{
int x,y;
extend_gcd(q,m,x,y);
//q的逆元就是x
x=(x%m+m)%m;
ans=(ans*x)%m;
}
}
int main()
{
int t,i,j,k;
while(scanf("%d%d",&n,&m))
{
if(n==0&&m==0)
break;
p=0; t=m;
for(i=2;i*i<=t;i++)
if(t%i==0)
{
prim[p++]=i;
while(t%i==0)
t/=i;
}
if(t>1)
prim[p++]=t;
__int64 ans=1,res=1,tmp;
//h(1)=1 h(2)=2 h(3)=5 h(4)=14
memset(num,0,sizeof(num));
for(i=2;i<=n;i++)
{
cal1(ans,4*i-2);
cal2(ans,i+1);
tmp=ans;
for(j=0;j<p;j++)
for(k=0;k<num[j];k++)
tmp=(tmp*prim[j])%m;
//tmp就是每一步的值
res=(res+tmp)%m;
}
printf("%I64d\n",res);
}
return 0;
}