其他分享
首页 > 其他分享> > 卡特兰数——网格

卡特兰数——网格

作者:互联网

原题链接

卡特兰数公式C_{2n}^n - C_{2n}^{n-1}=\frac{C_{2n}^n}{n + 1}

变形一下C_{n + m}^n - C_{n + m}^{m - 1}

用分解质因数求组合数解

#include<iostream>
#include<cmath>
#include<vector>

using namespace std;

typedef long long LL;
const int N = 25050;
int primes[N], cnt;
int sum[N];
bool st[N];
int x, y;

void get_primes(int n)//线性筛
{
    for (int i = 2; i <= n; i++)
    {
        if (!st[i])
        {
            primes[cnt++] = i;
        }
        for (int j = 0; primes[j] <= n / i; j++)
        {
            st[primes[j] * i] = true;
            if (i % primes[j] == 0)break;
        }
    }
}

int get(LL a, LL p)
{
	int num = 0;
	while (a)
	{
		num += a / p; a /= p;
	}
	return num;
}

void get_sum(int a, int b)
{
	for (int i = 0; i < cnt; i++)
	{
		int p = primes[i];
		sum[i] = get(a, p) - get(b, p) - get(a - b, p);
	}
}

vector<int > mul(vector<int> &a, int b)
{
	vector<int> c;
	int t = 0;
	for (int i = 0; i < a.size() || t; i++)
	{
		if (i < a.size())t += a[i] * b;
		c.push_back(t % 10);
		t /= 10;
	}
	return c;
}

void get_ans(vector<int> &res, int a, int b)
{
	get_sum(a, b);
	for (int i = 0; i < cnt; i++)
	{
		for (int j = 0; j < sum[i]; j++)
		{
			res = mul(res, primes[i]);
		}
	}
}
vector<int> sub(vector<int>& a, vector<int>& b) {
	
	vector<int> c;
	int t = 0;//进位
	for (int i = 0; i < a.size(); i++)
	{
		t = a[i] - t;
		if (i < b.size())t = t - b[i];
		c.push_back((t + 10) % 10);
		if (t < 0)t = 1;
		else t = 0;
	}
	while (c.size() > 1 && c.back() == 0)c.pop_back();//去除前导 0
	return c;
}

int main()
{
	cin >> x >> y;
	
	int a = x + y, b = x, c = y - 1;
	
	get_primes(a);
	vector<int> res, ans;
	res.push_back(1), ans.push_back(1);
		
	get_ans(res, a, b);
	get_ans(ans, a, c);
	
	ans = sub(res, ans);
	
	for (int i = ans.size() - 1; i >= 0; i--)cout << ans[i];
	cout << endl;
		
	return 0;
}

标签:get,int,res,网格,vector,ans,卡特兰,size
来源: https://blog.csdn.net/qq_56427460/article/details/122389947