poj 2084 Game of Connections (卡特兰数,大数乘除)

题目链接:http://poj.org/problem?id=2084


关于卡特兰数,可以看看下面这几个博客,原来这么有用。。。

http://blog.sina.com.cn/s/blog_7064e7850100y1xf.html

http://blog.csdn.net/hackbuteer1/article/details/7450250


看懂了卡特兰数,一个公式就能解决这个题,但是问题在于数太大了,要用到大数的乘除法。

参考博客:http://blog.csdn.net/hnust_xiehonghao/article/details/8062374   感谢!!!

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int base = 10000;  //10000进制 
const int maxn = 110;
void multiply(int* a, int maxn, int b) {
	int i, jw = 0;
	for(i = maxn - 1; i >= 0; i--) {
		jw += a[i] * b;  //进位 
		a[i] = jw % base;
		jw /= base;
	}
}
void divide(int* a, int maxn, int b) {
	int i, jw = 0;
	for(i = 0; i < maxn; i++) {
		jw = jw * base + a[i]; //借位 
		a[i] = jw / b;
		jw %= b;
	}
}
int main() {
	int a[110][maxn];
	memset(a[1], 0, sizeof(a[1]));
	a[1][maxn - 1] = 1;
	int i;
	for(i = 2; i <= 100; i++) {  //打表 
		memcpy(a[i], a[i - 1], sizeof(a[i]));
		multiply(a[i], maxn, 4 * i - 2);
		divide(a[i], maxn, i + 1);
	}
	int n;
	while(~scanf("%d", &n)) {
		if(n == -1) break;
		for(i = 0; i < maxn && a[n][i] == 0; i++); //找到首位 
		printf("%d", a[n][i++]);  //前几位要特别输出,因为首位不能为零 
		for(; i < maxn; i++) {
			printf("%04d", a[n][i]);
		}
		printf("\n");
	}
	return 0;
}


你可能感兴趣的:(poj 2084 Game of Connections (卡特兰数,大数乘除))