HDU 3037 Saving Beans 大组合数 lucas定理

直接lucas降到10w以内搞组合数

#include <cstdio>
#include <cstring>
typedef __int64 LL;
LL f[110010];
LL pow(LL a, LL b, LL c)
{
	LL ans = 1;
	while(b)
	{
		if(b&1)
			ans = (ans*a) % c;
		b >>= 1;
		a = (a*a) % c;
	}
	return ans;
}
LL cm(LL n, LL m, LL p)
{
	if(n < m)
		return 0;
	return (f[n]*pow(f[m]*f[n-m]%p, p-2, p))%p;
}
LL lucas(LL n, LL m, LL p)
{
	if(m == 0)
		return 1;
	return (cm(n%p, m%p, p)*lucas(n/p, m/p, p))%p;
}
int main()
{
	int T;
	scanf("%d", &T);
	
	while(T--)
	{
		LL n, m, p;
		scanf("%I64d %I64d %I64d", &n, &m, &p);
		f[0] = 1;
		for(int i = 1; i <= p; i++)
			f[i] = f[i-1]*i%p;
		printf("%I64d\n", lucas(n+m, m, p));
	}
	return 0;
}


你可能感兴趣的:(HDU 3037 Saving Beans 大组合数 lucas定理)