HDU 5446 Unknown Treasure Lucas定理+中国剩余定理

数学本来就弱,现在大半年不练,果断简单题都不会了。。。先用lucas求出x mod 每一个素数结果,然后再用中国剩余定理解出x,不过要自己写乘法,防溢出。。。
#include <cstdio>
#include <cstring>
using namespace std;
typedef __int64 LL;
LL a[12], mm[12];
LL mul(LL a, LL b, LL c)
{
    LL ans = 0;
    while(b)
    {
        if(b&1)
        {
            ans += a;
            ans %= c;
        }
        a += a;
        a %= c;
        b >>= 1;
    }
    return ans;
}
LL pow(LL a, LL b, LL c)
{
    LL ans = 1;
    while(b)
    {
        if(b&1)
            ans = mul(ans, a, c);
        b >>= 1;
        a = mul(a, a, c);
    }
    return ans;
}

LL cm(LL n, LL m, LL p)
{
    if(n < m)
        return 0;
    if(m > n-m)
        m = n-m;
    LL s1 = 1, s2 = 1;
    for(LL i = 0;i < m; i++)
    {
        s1 = mul(s1, (n-i), p);
        s2 = mul(s2, (i+1), p);
    }
    return mul(s1, pow(s2, p-2, p), p);
}
LL lucas(LL n, LL m, LL p)
{
    if(m == 0)
        return 1;
    //puts("asf");
    return mul(cm(n%p, m%p, p), lucas(n/p, m/p, p), p);
}
void gcd(LL a, LL b, LL& d, LL& x, LL& y)
{
	if(!b)
	{
		d = a;
		x = 1;
		y = 0;
	}
	else
	{
		gcd(b, a%b, d, y, x);
		y -= x * (a/b);
	}
}

LL china(LL n, LL* a, LL* mm)
{
	LL M = 1, d, y, x = 0;
	for(int i = 0; i < n; i++)
		M *= a[i];
	for(int i = 0; i < n; i++)
	{
		LL w = M /a[i];
		gcd(a[i], w, d, d, y);
		x = (x + mul(mul(y, w, M), mm[i], M)) % M;
	}
	return (x+M)%M;
}
int main()
{
    int T;
    scanf("%d", &T);
    while(T--)
    {
        LL n, m, k;
        scanf("%I64d %I64d %I64d", &n, &m, &k);
        for(int i = 0; i < k; i++)
        {
            scanf("%I64d", &a[i]);
        }
        for(int i = 0; i < k; i++)
        {
            mm[i] = lucas(n, m, a[i]);
        }
        printf("%I64d\n", china(k, a, mm));
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值