Problem 1775 Counting Binary Trees
Accept: 92 Submit: 296
Time Limit: 3000 mSec Memory Limit : 32768 KB
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
3 100 4 10 0 0
Sample Output
8 2
Source
2009 NIT Cup National Invitation Contest
解析:卡特兰数的大数取模,求逆元
当式子带除法时, 这里的做法是把除法变为乘法, 再用上面的方法来解.我们知道,a / b % m == a * ((b^-1) % m) % m, 其中b^-1是b关于m的逆元, 可用扩展欧几里德求得,但是前提条件是b与m互质, 而这题的m是任意的, 所以不能直接求逆元, 但可以通过一些处理使得互质条件满足.其实只需要把答案看做两部分的乘积:一部分是与m互素的,这一部分的乘法直接计算,除法改成乘逆元就行了;另一部分是若干个m的素因子的乘积,因为m<1,000,000,000,所以m的不同素因子不会太多,用一个数组记录每一个素因子的数量就行。这一部分的乘法(4*i-2)就是把记录的素因子数量相加,除法(i+1)就是把记录的素因子数量相减。最后计算这两部分的乘积对m的取模,也就是h(i)%m,递推求和。
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
//1 ≤ n ≤ 100,000, 1 ≤ m ≤ 10^9
//计算第n个卡特兰数%m 即h(n)=(2n)!/(n!*(n+1)!)%m
//h(0)=1,h(i)=h(i-1)*(4*i-2)/(i+1)。
int n,m;
int sm[1000],p;//将m分解质因数
int sa[1000];//4*i-2 和 i+1 分解质因数
//素数筛选
int flag[50000],pri[50000],pl;
void prime()
{
for(int i=2;i<50000;i++)
{
if(flag[i]==0) pri[pl++]=i;
for(int j=0;j<pl&&i*pri[j]<50000;j++)
{
flag[i*pri[j]]=1;
if(i%pri[j]==0) break;
}
}
}
int extgcd(int a,int b,int &x,int &y)
{
if(b==0)
{
x=1,y=0;
return a;
}
int r=extgcd(b,a%b,x,y);
int t=x;x=y;y=t-a/b*y;
return r;
}
__int64 cal()
{
__int64 sum=1,res=1;//n=1时 sum=1 后面从2开始
p=0;
int tm=m;//将m分解质因数
for(int i=0;pri[i]*pri[i]<=tm;i++)
{
if(tm%pri[i]==0)
{
sm[p++]=pri[i];
while(tm%pri[i]==0) tm/=pri[i];
}
}
if(tm>1) sm[p++]=tm;//important
memset(sa,0,sizeof(sa));
for(int i=2;i<=n;i++)
{
int t;
t=4*i-2;
for(int j=0;j<p;j++)
{
while(t%sm[j]==0)
{
sa[j]++,t/=sm[j];
}
}
res=res*t%m;
t=i+1;
for(int j=0;j<p;j++)
{
while(t%sm[j]==0)
{
sa[j]--,t/=sm[j];
}
}
if(t>1)
{
int x,y;
int r=extgcd(t,m,x,y);
x=(x%m+m)%m;
res=res*x%m;
}
__int64 tmp=res;
for(int j=0;j<p;j++)
{
for(int k=0;k<sa[j];k++)
{
tmp=tmp*sm[j]%m;
}
}
sum=(sum+tmp)%m;
}
return sum;
}
int main()
{
prime();
while(scanf("%d%d",&n,&m)==2&&n)
{
__int64 ans=cal();
printf("%I64d/n",ans);
}
return 0;
}