bzoj2875: [Noi2012]随机数生成器
题目链接
题解
递推式有了,那就愉快的矩阵快速幂
代码
/*
递推式子都给你了,那就愉快的矩阵快速幂呗
*/
#include<cstdio>
#include<cstring>
#include<algorithm>
#define LL long long
LL m,a,c,x0,n,g;
LL mul(LL x, LL y) {
LL ret = 0;
for(;y;y >>= 1, x = (x + x) % m)
if(y & 1) ret = (ret + x) % m;
return ret % m;
}
struct Matrix {
LL a[3][3];
int r,c;
Matrix() {memset(a,0,sizeof a);r = 0,c = 0;}
Matrix operator * (const Matrix &A) const {
Matrix ret; ret.r = r,ret.c = A.c;
for(int i = 0;i < r;++ i)
for(int j = 0;j < A.c;++ j)
for(int k = 0;k < c;++ k)
ret.a[i][j] = (ret.a[i][j] + mul(a[i][k] , A.a[k][j]) ) % m;
return ret;
}
} f;
Matrix fstpow() {
Matrix ret;
ret.r = 2,ret.c = 2;
ret.a[0][0] = 1,ret.a[1][1] = 1;
for(;n;n >>= 1ll,f = f * f)
if(n & 1ll) ret = f * ret;
return ret;
}
int main() {
scanf("%lld%lld%lld%lld%lld%lld",&m,&a,&c,&x0,&n,&g);
f.r = 2,f.c = 2;
f.a[0][0] = a;f.a[1][1] = f.a[0][1] = 1;
Matrix ans; ans.r = 2,ans.c = 1;
ans.a[0][0] = x0; ans.a[1][0] = c;
Matrix tmp = fstpow();
ans = tmp * ans;
printf("%lld\n",ans.a[0][0] % g);
return 0;
}