首页 > 代码库 > 【BZOJ】2875: [Noi2012]随机数生成器(矩阵乘法+快速乘)

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

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

矩阵的话很容易看出来。。。。。我就不写了。太水了。

然后乘法longlong会溢出。。。那么我们用快速乘。。。就是将快速幂的乘法变成加法。。。这种很简单吧。。

#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 read(a) a=getint()#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;}

  

 


 

 

Description

 

Input

包含6个用空格分割的m,a,c,X0,n和g,其中a,c,X0是非负整数,m,n,g是正整数。

Output

输出一个数,即Xn mod g

Sample Input


11 8 7 1 5 3


Sample Output

2

HINT

 

Source

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