HDU1033 Buy the Ticket(卡特兰 大数)
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1133 #include<stdio.h> #include <string.h> #include<stdlib.h> #define M 10000 char str[M]; //算100以内的阶乘,存放在fact里面 char fact[205][M]; //用字符串表示大数,以'#'号结尾 //str1和str2是乘数,str是结果 int Mutiply(char *str1,char *str2,char *str) { int i,j; int a,b; int Result[M]; memset(Result,sizeof(Result)); for(i = 0; str1[i] != '#'; ++i) { a = (int)(str1[i] - '0'); for(j = 0; str2[j] != '#'; ++j) { b = (int)(str2[j] - '0'); Result[i + j] += a * b; } } j += i - 1; i = 0; //到了最高位,如果不为零,就一直赋值。 for(i = 0; (i < j || Result[i] > 0); ++i) { str[i] = Result[i] % 10 + '0'; Result[i+1] += Result[i] / 10; } str[i] = '#';//加结束标志 return i; } //nLen表示所有字符的个数 void Invert(char *str,int nLen) { int i; char temp; for(i = 0; i < (nLen >> 1); ++i) { temp = str[i]; str[i] = str[nLen - i - 1]; str[nLen - i - 1] = temp; } } void Print(char *str,int nLen)//打印 { int i; for(i = 0; i < nLen; ++i) { putchar(str[i]); } printf("n"); } //计算阶乘 int Fact(int a,int b) { char buf[15]; int nLen; fact[0][0] = '0'; fact[1][0] = '1'; fact[1][1]= '#';//记得加结束标志 for(int i = 2; i <= a; ++i) { if(i == b) { memcpy(fact[i],fact[i - 1],(nLen + 2) * sizeof(char)); continue; } itoa(i,buf,10); nLen = strlen(buf); buf[nLen] = '#';//记得加结束标志 buf[nLen + 1] = 0; Invert(buf,nLen); nLen = Mutiply(fact[i - 1],fact[i]); fact[i][nLen] = '#';//记得加结束标志 } return nLen; } void main() { int m,n; int nLen; int t = 1; char buf[5]; while (scanf("%d %d",&m,&n)) { if(!m && !n) { break; } if(m < n) { printf("Test #%d:n0n",t++); continue; } nLen = Fact(m+n,m+1); printf("Test #%d:n",t++); if(n)//如果n不为零,则需要乘(m-n+1) { itoa(m - n + 1,10); nLen = strlen(buf); buf[nLen] = '#'; buf[nLen + 1] = 0; Invert(buf,nLen); nLen = Mutiply(fact[m+n],str); Invert(str,nLen); Print(str,nLen); } else { Invert(fact[m],nLen); Print(fact[m],nLen); } } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |