hdu Train Problem II

来源:互联网 发布:伦拜亚斯对乔丹数据 编辑:程序博客网 时间:2024/05/19 21:01
http://acm.hdu.edu.cn/showproblem.php?pid=1023
此题是卡特兰数对出栈次序的应用,首先要知道卡特兰数的递推公式:
h[1]=1;
h[n]=h[n-1]*(4*n-2 )/(n+1);
由于卡特兰数递增速度相当快,当n=20,h[20]=6564120420;
因此该题要用上高精度 乘除法运算
代码与解析:
#include<iostream>
using namespace std;
int a[120][120],b[120];                  //a为高精度卡特兰数,b为卡特兰数的长度
void catalan()
{
int i,j,len,carry,temp;              
len=1;
a[1][0]=1;                           //卡特兰数第一项为1
b[1]=1;
for(i=2;i<=100;i++)
{
for(j=0;j<len;j++)
a[i][j]=a[i-1][j]*(4*i-2);   //递推公式单位相乘;将第i项卡特兰数的len位数分别储存在a[i][0]-a[i][len-1]中
carry=0;
for(j=0;j<len;j++)
{
temp=a[i][j]+carry;       
a[i][j]=temp%10;
carry=temp/10;               //进位;进位后的数设为temp,carry记录所进位的数
}
while(carry)
{
a[i][len++]=carry%10;       //继续进位,数组伸长
carry/=10;
}
for(j=len-1;j>=0;j--)
{
temp=carry*10+a[i][j];     //每位相除;如121÷3该运算过程可由此检验
a[i][j]=temp/(i+1);
carry=temp%(i+1);
}
while(!a[i][len-1])            //去除高位零
{
len--;
}
b[i]=len;
}
}
void main()
{
catalan();
int n,i;
while(cin>>n)
{
for(i=b[n]-1;i>=0;i--)
{
cout<<a[n][i];
}
cout<<endl;
}
}
原创粉丝点击