P2044 [NOI2012] 随机数生成器

P2044 [NOI2012] 随机数生成器

解题思路:

[ x [ i − 1 ] c ] ∗ [ a 0 1 1 ] = [ x [ i ] c ] \begin{bmatrix}x[i-1]&c\end{bmatrix}*\begin{bmatrix}a& 0\\1&1\end{bmatrix}= \begin{bmatrix}x[i]&c\end{bmatrix} [x[i1]c][a101]=[x[i]c]
注意:相乘可能爆long long,所以需要龟速乘。

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef long double lf;
typedef unsigned long long ull;
typedef pair<int,int>P;
const int inf = 0x7f7f7f7f;
const ll INF = 1e16;
const int N = 1e5+10;
//const ll mod = 1e9+7;
const double PI = acos(-1.0);
const double eps = 1e-4;

inline int read(){int x=0,f=1;char ch=getchar();while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}return x*f;}
inline string readstring(){string str;char s=getchar();while(s==' '||s=='\n'||s=='\r'){s=getchar();}while(s!=' '&&s!='\n'&&s!='\r'){str+=s;s=getchar();}return str;}
int random(int n){return (int)(rand()*rand())%n;}
void writestring(string s){int n = s.size();for(int i = 0;i < n;i++){printf("%c",s[i]);}}


typedef struct node{
    ll mx[3][3];
}mx;

ll Wuguidechengfa(ll x,ll y,ll mod){
	ll ans=0;
	while(y){
		if(y&1) (ans+=x)%=mod;
		(x+=x)%=mod;
		y>>=1;
	}
	return ans;
}
mx multiply(mx a,mx b,ll mod){
    mx c;
    for(int i = 1;i <= 2;i++){
        for(int j = 1;j <= 2;j++){
            c.mx[i][j] = 0;
            for(int k = 1;k <= 2;k++){
                c.mx[i][j] = (c.mx[i][j]+Wuguidechengfa(a.mx[i][k],b.mx[k][j],mod))%mod;
            }
        }
    }
    return c;
}
mx fast_power(mx a,ll p,ll mod){
    mx ans;
    ans.mx[1][1]=ans.mx[2][2]=1;
    ans.mx[1][2]=ans.mx[2][1]=0;
    while(p){
        if(p&1) ans = multiply(ans,a,mod);
        p >>= 1;
        a = multiply(a,a,mod);
    }
    return ans;
}
int main(){
//    srand((unsigned)time(NULL));
    mx base;
    base.mx[1][2]=0;base.mx[2][1]=1;base.mx[2][2]=1;
    ull m,a,c,x0,n,g;
    cin >> m >> a >> c >> x0 >> n >> g;
    base.mx[1][1] = a%m;
    c %= m;
    x0 %= m;//x0,c,a
    base = fast_power(base,n,m);
    ll ans = ((Wuguidechengfa(x0,base.mx[1][1],m))+(Wuguidechengfa(c,base.mx[2][1],m)))%m;
    ans %= g;
    cout<<ans<<endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_42868863/article/details/113792530