bzoj2875随机数生成器——矩阵快速幂

题目:https://www.lydsy.com/JudgeOnline/problem.php?id=2875

矩阵快速幂,把x和c分开求,最后加上即可;

为防止爆long long,要用快速乘。

代码如下:

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
typedef long long ll;
ll n,x,a,c,m,g;
ll mul(ll x,ll y)
{
    ll s=0;
    while(y)
    {
        if(y&1)(s+=x)%=m;
        x=(x+x)%m;
        y/=2;
    }
    return s;
}
struct Matrix{
    ll aa[3][3];
    Matrix operator * (const Matrix &y) const
    {
        Matrix x;
        memset(x.aa,0,sizeof x.aa);
        for(int i=1;i<=2;i++)
            for(int k=1;k<=2;k++)
                for(int j=1;j<=2;j++)
                    (x.aa[i][j]+=mul(aa[i][k],y.aa[k][j]))%=m;
        return x;
    }
}ans,s;
int main()
{
    scanf("%lld%lld%lld%lld%lld%lld",&m,&a,&c,&x,&n,&g);
    s.aa[1][1]=a;s.aa[1][2]=0;
    s.aa[2][1]=c;s.aa[2][2]=1;
    ans.aa[1][1]=1;ans.aa[2][2]=1;
    while(n)
    {
        if(n&1)ans=s*ans;
        s=s*s;
        n/=2;
    }
    printf("%lld",(mul(ans.aa[1][1],x)+ans.aa[2][1])%m%g);
    return 0;
}
原文地址:https://www.cnblogs.com/Zinn/p/9043528.html