Counting Binary Trees
Time Limit: 6000/3000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 493 Accepted Submission(s): 151
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 .
?
?
?
?
?
?
#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;
__int64 vec[40],num[40],m,index;
__int64 ectgcd(__int64 a,__int64 b,__int64 & x,__int64 & y)
{
if(b==0){x=1;y=0;return a;}
__int64 d=ectgcd(b,a%b,x,y);
__int64 t=x;x=y;y=(t-a/b*y);
return d;
}
int main()
{
__int64 i,j,tempm,t,k,l;
__int64 n;
while(scanf("%I64d%I64d",&n,&m)!=EOF&&n+m)
{
memset(num,0,sizeof(num));
index=0;
tempm=m;
for(i=2;i*i<=m;i++)
{
if(m%i==0)
{
vec[index++]=i;
while(m%i==0)
{
m=m/i;
}
}
}
if(m!=1)
vec[index++]=m;
m=tempm;
__int64 res=1,result=0;
for(i=1;i<=n;i++)
{
k=4*i-2;
for(j=0;j<index;j++)
{
if(k%vec[j]==0)
{
while(k%vec[j]==0)
{
k=k/vec[j];
num[j]++;
}
}
}
res=res*k%m;
k=i+1;
for(j=0;j<index;j++)
{
if(k%vec[j]==0)
{
while(k%vec[j]==0)
{
k=k/vec[j];
num[j]--;
}
}
}
if(k!=1)
{
__int64 x,y;
ectgcd(k,m,x,y);
x=x%m;
if(x<0)
x+=m;
res=res*x%m;
}
l=res;
for(j=0;j<index;j++)
for(t=0;t<num[j];t++)
l=l*vec[j]%m;
result=(result+l)%m;
}
printf("%I64d\n",result);
}
return 0;
}
?
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061
微信掃一掃加我為好友
QQ號(hào)聯(lián)系: 360901061
您的支持是博主寫(xiě)作最大的動(dòng)力,如果您喜歡我的文章,感覺(jué)我的文章對(duì)您有幫助,請(qǐng)用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長(zhǎng)非常感激您!手機(jī)微信長(zhǎng)按不能支付解決辦法:請(qǐng)將微信支付二維碼保存到相冊(cè),切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對(duì)您有幫助就好】元

