您的位置:首页 > 其它

HDU 3240 Counting Binary Trees [卡特兰数] 【数论+组合数学】

2016-07-26 10:43 651 查看
题目连接 :http://acm.hdu.edu.cn/showproblem.php?pid=3240

—————————————————————————–.

Counting Binary Trees

Time Limit: 6000/3000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)

Total Submission(s): 739 Accepted Submission(s): 256

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 <= 109) 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 Invitational Contest

——————————————.

题目大意 : 就是让你求 卡特兰数对M取模的结果

题解 :

卡特兰数主要有两种

一般式 :


另类递归式: h(n)=((4*n-2)/(n+1))*h(n-1);

在这里我们用的是递归式求解卡特兰数

注意我们求解的是卡特兰数的前N项和 h(1)=1 h(2)=2 h(3)=5 h(4)=14

根据递归式很容易想到(4*n-2)/(n+1) 求它的值然后不断乘起来就行 首先想到分子可以直接累乘 分母每一步计算一下乘上逆元即可

但是求逆元的要求就是分子分母互质 所以我们想到分解下m 的质因子 然后最分式上下约分处理 这个时候就可以用一个数组来存储分式中M的每个素因子个数 分子的就加一 分母的就减一

最后计算就行了

附本题代码

——————————————–.

#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <string>
#include <math.h>
#include <stdlib.h>
#include <time.h>
#include <queue>
using namespace std;

#define LL long long int
#define _LL __int64

const LL  MOD  = 1e9+7;
const int MAX  = 105;
const int MIN  = 1005;
const double EPS=1e-6;

int prime[10005];
int num[10005];
int k=0;

LL qmod(LL a,LL b,LL c)
{
LL res=1;
while(b)
{
if(b&1) res=(res*a)%c;
b >>= 1;
a=(a*a)%c;
}
return res;
}

LL extendeuclid(LL a,LL b,LL &x,LL &y)
{
if(b==0)
{
x=1,y=0;
return a;
}
else
{
LL r = extendeuclid(b,a%b,x,y);
LL t = x;
x = y;
y = t-(a/b)*y;
return r;
}
}

int n,m;
LL ans;

void cal1(int nn)
{
for(int i=0; i<k; i++)
{
// if(nn<prime[i]) break;
while(nn%prime[i]==0)
{
nn/=prime[i];
num[i]++;
}
}

ans = (ans * nn)%m;
//  printf("%I64d\n",ans);
}

void cal2(int nn)
{
for(int i=0; i<k; i++)
{
// if(nn<prime[i]) break;
while(nn%prime[i]==0&&num[i]>0)
{
nn/=prime[i];
num[i]--;
}
}

if(nn>1)
{
LL x,y;
extendeuclid(nn,m,x,y);

x=(x%m+m)%m;
ans=(ans*x)%m;
}
}

int main()
{
while(~scanf("%d%d",&n,&m)&&(n||m))
{
int tem=m;k=0;
for(int i=2; i*i<=tem; i++)
{
if(tem%i==0) prime[k++]=i;
while(tem%i==0) tem/=i;
}
if(tem>1) prime[k++]=tem;

/*
for(int i=0;i<k;i++)
printf("%d\n",prime[i]);
puts("**********");
*/

ans=1;
LL res=1,tmp;
//h(1)=1 h(2)=2 h(3)=5 h(4)=14
memset(num,0,sizeof(num));
for(int i=2; i<=n; i++)
{
cal1(4*i-2);
cal2(i+1);
tmp=ans;

// for(int j=0;j<k;j++)
//    tmp=(tmp*qmod(prime[j],num[j],m))%m;

for(int j=0;j<k;j++)
for(int o=0;o<num[j];o++)
tmp=(tmp*prime[j])%m;

res=(res+tmp)%m;  //res=h(0)=1;
}
printf("%I64d\n",res);

}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: