# 【BZOJ】2875: [Noi2012]随机数生成器（矩阵乘法+快速乘）

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

#include <cstdio>
#include <cstring>
#include <cmath>
#include <string>
#include <iostream>
#include <algorithm>
#include <queue>
#include <set>
#include <map>
using namespace std;
typedef unsigned long long ll;
#define rep(i, n) for(int i=0; i<(n); ++i)
#define for1(i,a,n) for(int i=(a);i<=(n);++i)
#define for2(i,a,n) for(int i=(a);i<(n);++i)
#define for3(i,a,n) for(int i=(a);i>=(n);--i)
#define for4(i,a,n) for(int i=(a);i>(n);--i)
#define CC(i,a) memset(i,a,sizeof(i))
#define print(a) printf("%d", a)
#define dbg(x) cout << (#x) << " = " << (x) << endl
#define error(x) (!(x)?puts("error"):0)
#define rdm(x, i) for(int i=ihead[x]; i; i=e[i].next)
inline const int getint() { int r=0, k=1; char c=getchar(); for(; c<'0'||c>'9'; c=getchar()) if(c=='-') k=-1; for(; c>='0'&&c<='9'; c=getchar()) r=r*10+c-'0'; return k*r; }

ll m, a, c, x0, n, g;
typedef ll mtx[2][2];

mtx t;
ll mul(ll a, ll b) {
ll ret=0;
while(b) {
if(b&1) ret=(ret+a)%m;
a=(a+a)%m;
b>>=1;
}
return ret;
}
void mtxmul(mtx a, mtx b, mtx c, int la, int lb, int lc) {
rep(i, la) rep(j, lc) {
t[i][j]=0;
rep(k, lb) t[i][j]=(t[i][j]+mul(a[i][k], b[k][j]))%m;
}
rep(i, la) rep(j, lc) c[i][j]=t[i][j];
}

mtx ma, mb, mc;
int main() {
cin >> m >> a >> c >>x0 >> n >> g;
ma[0][0]=x0; ma[0][1]=1;
mb[0][0]=a; mb[0][1]=0;
mb[1][0]=c; mb[1][1]=1;
mc[0][0]=mc[1][1]=1;
while(n) {
if(n&1) mtxmul(mc, mb, mc, 2, 2, 2);
n>>=1;
mtxmul(mb, mb, mb, 2, 2, 2);
}
mtxmul(ma, mc, ma, 2, 2, 2);
printf("%llu\n", ma[0][0]%g);
return 0;
}


11 8 7 1 5 3

2

## Source

posted @ 2014-12-07 11:37  iwtwiioi  阅读(220)  评论(0编辑  收藏