• BZOJ2875 & 洛谷2044:[NOI2012]随机数生成器——题解


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

    https://www.luogu.org/problemnew/show/P2044

    栋栋最近迷上了随机算法,而随机数是生成随机算法的基础。栋栋准备使用线性同余法(Linear Congruential Me

    thod)来生成一个随机数列,这种方法需要设置四个非负整数参数m,a,c,X[0],按照下面的公式生成出一系列随机
    数X[n]X[n+1]=(aX[n]+c)mod m其中mod m表示前面的数除以m的余数。从这个式子可以看出,这个序列的下一个数
    总是由上一个数生成的。用这种方法生成的序列具有随机序列的性质,因此这种方法被广泛地使用,包括常用的C+
    +和Pascal的产生随机数的库函数使用的也是这种方法。栋栋知道这样产生的序列具有良好的随机性,不过心急的
    他仍然想尽快知道X[n]是多少。由于栋栋需要的随机数是0,1,...,g-1之间的,他需要将X[n]除以g取余得到他想要
    的数,即X[n] mod g,你只需要告诉栋栋他想要的数X[n] mod g是多少就可以了。

    被带偏了想找循环节结果发现是m的……mmp。

    实际上可以直接用矩阵乘法来表达。

    |a c| |xn| |xn+1|

    |0 1| |1  | |1     |

    恩没了。

    #include<cmath>
    #include<stack>
    #include<queue>
    #include<cstdio>
    #include<cctype>
    #include<vector>
    #include<cstdlib>
    #include<cstring>
    #include<iostream>
    #include<algorithm>
    using namespace std;
    typedef long long ll;
    inline ll read(){
        ll X=0,w=0;char ch=0;
        while(!isdigit(ch)){w|=ch=='-';ch=getchar();}
        while(isdigit(ch))X=(X<<3)+(X<<1)+(ch^48),ch=getchar();
        return w?-X:X;
    }
    ll n,p,a,c,x0;
    int g;
    inline ll multi(ll x,ll y){
        ll res=0;
        while(y){
        if(y&1)(res+=x)%=p;
        (x+=x)%=p;y>>=1;
        }
        return res;
    }
    struct matrix{
        ll g[2][2];
        matrix(){
        memset(g,0,sizeof(g));
        }
        matrix operator *(const matrix &b)const{
        matrix c;
        for(int i=0;i<2;i++)
            for(int j=0;j<2;j++)
            for(int k=0;k<2;k++)
                (c.g[i][j]+=multi(g[i][k],b.g[k][j]))%=p;
        return c;
        }
    };
    inline matrix qpow(matrix x,ll y){
        matrix res;
        res.g[0][0]=res.g[1][1]=1;
        while(y){
        if(y&1)res=res*x;
        x=x*x;y>>=1;
        }
        return res;
    }
    int main(){
        p=read(),a=read(),c=read(),x0=read(),n=read(),g=read();
        matrix A,B;
        A.g[0][0]=a;A.g[0][1]=c;A.g[1][1]=1;B.g[0][0]=x0;B.g[1][0]=1;
        A=qpow(A,n);B=A*B;
        printf("%lld
    ",B.g[0][0]%g);
        return 0;
    }

    +++++++++++++++++++++++++++++++++++++++++++

     +本文作者:luyouqi233。               +

     +欢迎访问我的博客:http://www.cnblogs.com/luyouqi233/+

    +++++++++++++++++++++++++++++++++++++++++++

  • 相关阅读:
    hdu 2199 Can you solve this equation? 二分
    STL 学习代码~
    hdu 1551 Cable master 二分
    fzu 1564 Combination 组合数是否包含因数
    fafu 1079 帮冬儿忙 组合数包含因数个数
    soj 3290 Distribute The Apples I 组合数对素数取余
    fzu 2020 组合 组合数对素数取余
    hdu 1969 Pie 二分
    hdu 2141 Can you find it? 二分
    hdu 2899 Strange fuction 二分
  • 原文地址:https://www.cnblogs.com/luyouqi233/p/9144063.html
Copyright © 2020-2023  润新知