分块计算

本文介绍了一道ACM竞赛题目中涉及的大规模模数计算问题及其解决方法。通过预处理和分段计算的方式避免了直接使用快速幂运算带来的效率问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:http://acm.upc.edu.cn/problem.php?id=2219

 

 

题意:

It's easy for ACMer to calculate A^X mod P. Now given seven integers n, A, K, a, b, m, P, and a

function f(x) which defined as following.

f(x) = K, x = 1

f(x) = (a*f(x-1) + b)%m , x > 1


Now, Your task is to calculate

( A^(f(1)) + A^(f(2)) + A^(f(3)) + ...... + A^(f(n)) ) modular P. 

 

本题有点技巧,不要直接快速幂运算,这里要分两部分,详见代码:

#include <iostream>
#include <string.h>
#include <stdio.h>

using namespace std;
typedef long long LL;

LL f[1000005];
LL x1[1000005];
LL x2[1000005];

LL quick_mod(LL a,LL b,LL m)
{
    LL ans=1;
    while(b)
    {
        if(b&1)
        {
            ans=ans*a%m;
            b--;
        }
        b>>=1;
        a=a*a%m;
    }
    return ans;
}

LL multi(LL n,LL p)
{
    return x1[n/50000]*x2[n%50000]%p;
}

int main()
{
    LL t,n,A,K,a,b,m,p,tt=1;
    LL ans;
    cin>>t;
    while(t--)
    {
        cin>>n>>A>>K>>a>>b>>m>>p;
        A%=p;a%=m;b%=m;
        f[1]=K;
        for(int i=2;i<=n;i++)
            f[i]=(f[i-1]%m*a%m+(b%m))%m;
        LL val=quick_mod(A,50000,p);
        x1[0]=1;
        for(int i=1;i<50001;i++)
            x1[i]=(val%p)*x1[i-1]%p;
        x2[0]=1;
        for(int i=1;i<50001;i++)
            x2[i]=(A%p)*x2[i-1]%p;
        ans=0;
        for(int i=1;i<=n;i++)
        {
            ans+=multi(f[i],p);
            ans%=p;
        }
        cout<<"Case #"<<tt++<<": ";
        cout<<ans<<endl;
    }
    return 0;
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值