分块计算

来源:互联网 发布:php沐辰的博客 编辑:程序博客网 时间:2024/05/16 12:27

题目: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;}


 

原创粉丝点击