hdu 1023 Train Problem II 【卡特兰数+大数】

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1023

卡特兰数公式:

令h(0)=1,h(1)=1,Catalan数满足递推式:h(n)= h(0)*h(n-1)+h(1)*h(n-2) + ... + h(n-1)*h(0) (n>=2)
例如:

h(2)=h(0)*h(1)+h(1)*h(0)=1*1+1*1=2
h(3)=h(0)*h(2)+h(1)*h(1)+h(2)*h(0)=1*2+1*1+2*1=5
另类递推式:h(n)=h(n-1)*(4*n-2)/(n+1);
递推关系的解为:h(n)=C(2n,n)/(n+1) (n=0,1,2,...)
递推关系的另类解为:h(n)=C(2n,n)-C(2n,n+1)(n=0,1,2,...)

 

卡特兰数的应用:
n对括号配对有多少种配对方式;
n个点构成的二叉树有多少种;
m+n个人买票,m人拿50元,n人拿100圆,一张票50,问有只要有拿100圆去买票就有50圆找零的情况有多少种(起初售票处没有50圆)     公式:( C(m+n,n) - C(m+n,m+1) ) * m! * n!= ( C(m+n,n) - C(m+n,n-1) ) * m! * n!

                     

本题只求卡特兰数,但是 h(100) 的数据范围超过longlong,所以要用大数
(然后发现自己不太会大数除法,看了别人的代码~~~)

#include<cstdio>
#include<iomanip>
#include<cstdlib>
#include<iostream>
#include<cstring>
#include<string>
#include<algorithm>
#include<math.h>
#include<map>
#include<set>
#include<queue>
#include<vector>
#include<stack>
#define inf 0x3f3f3f3f
using namespace std;
typedef long long ll;
const double pi=acos(-1.0);
const ll mod=1000;
const int N=1e2+10;
const int M=100000;//每个数组存五位

int ans[N][N];
//ans[i][0]表示每个卡特兰数的位数
void mark_catalan()
{
    ans[1][0]=ans[1][1]=1;
    for(int i=2; i<=100; i++)
    {
        int x=4*i-2,t=0,tmp=0;
        ans[i][0]=ans[i-1][0];
        for(int j=1; j<=ans[i][0]; j++)
        {
            ans[i][j]=(ans[i-1][j]*x+t)%M;
            t=(ans[i-1][j]*x+t)/M;
        }
        if(t!=0)
        {
            ans[i][ans[i][0]+1]=t;
            ans[i][0]++;
        }
        x=i+1;
        t=0;
        for(int j=ans[i][0]; j>=1; j--)
        {
            tmp=(ans[i][j]+t*M)%x;
            ans[i][j]=(ans[i][j]+t*M)/x;
            t=tmp;
        }
        if(ans[i][ans[i][0]]==0)
            ans[i][0]--;
    }
}

int main()
{
    int n;
    memset(ans,0,sizeof(ans));
    mark_catalan();
    while(~scanf("%d",&n))
    {
        printf("%d",ans[n][ans[n][0]]);
        for(int i=ans[n][0]-1; i>=1; i--)//非高位要补0
            printf("%05d",ans[n][3]);
        printf("\n");
    }
    return 0;
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值