BZOJ2875: [Noi2012]随机数生成器
【传送门:BZOJ2875】
简要题意:
给出m,a,c,x[0],并且x数组满足x[i]=(a*x[i-1]+c)%m(i≠0)
给出n,g,求出x[n]%g
题解:
显然用矩乘做,不过用矩乘时,要加long long,而且要用快速乘法来处理两个数之间的乘法,不然会爆long long
参考代码:
#include<cstdio> #include<cstring> #include<cstdlib> #include<algorithm> #include<cmath> using namespace std; typedef long long LL; struct node { LL a[3][3]; node() { memset(a,0,sizeof(a)); } }sum,cmp; LL m; LL f_mul(LL a,LL b) { LL ans=0; while(b!=0) { if(b%2LL==1LL) ans=(ans+a)%m; a=(a+a)%m;b/=2LL; } return ans; } node chengfa(node a,node b) { node c; for(int i=1;i<=2;i++) { for(int j=1;j<=2;j++) { for(int k=1;k<=2;k++) { c.a[i][j]=(c.a[i][j]+f_mul(a.a[i][k],b.a[k][j]))%m; } } } return c; } node p_mod(node a,LL b) { node ans; ans.a[1][1]=1;ans.a[2][2]=1; while(b!=0) { if(b%2LL==1LL) ans=chengfa(ans,a); a=chengfa(a,a); b/=2LL; } return ans; } int main() { LL a,c,x,n,g; scanf("%lld%lld%lld%lld%lld%lld",&m,&a,&c,&x,&n,&g); sum.a[1][1]=x;sum.a[1][2]=c; cmp.a[1][1]=a; cmp.a[2][1]=1;cmp.a[2][2]=1; sum=chengfa(sum,p_mod(cmp,n)); printf("%lld\n",sum.a[1][1]%g); return 0; }
渺渺时空,茫茫人海,与君相遇,幸甚幸甚