您的位置:首页 > 其它

codevs1281-线性递推

2016-02-26 21:56 369 查看


1281 Xn数列

 时间限制: 1 s

 空间限制: 128000 KB

 题目等级 : 大师 Master


题解

 查看运行结果

题目描述 Description

给你6个数,m, a, c, x0, n, g
Xn+1 = ( aXn +
c ) mod m,求Xn
m, a, c, x0, n, g<=10^18

输入描述 Input Description

一行六个数 m, a, c, x0, n, g

输出描述 Output Description

输出一个数 Xn mod g

样例输入 Sample Input

11 8 7 1 5 3

样例输出 Sample Output

2

数据范围及提示 Data Size & Hint

int64按位相乘可以不要用高精度。

不是很难的题,不过精度上有点坑。
线性递推要构造这个一个矩形T,初始矩形乘上T得到下一项的矩形,并且可以连乘下去。
于是假设有一个矩形[xn-1]  考虑在它之前乘上一个[a,c],这样不可行,就给前面补一个无关的1
于是变成了 [a,c]                 *  [xn-1]                   ,这样下一个矩形的(1,1)的位置就是xn了,但是这样的矩形不仅不能做乘法,还不能连续的乘下去                                    [ 1   ]    
要下一个矩形的【2,1】的位置是1,就在前面的矩形填上0,1
就变成了
[a,c]  *  [xn-1]         =     [axn-1+c]    =    [ xn ]
[0,1]      [ 1 ]                   [   1    ]              [ 1  ]

所以前面的矩形就是我们要的T了,将T连乘n次,在乘上初始矩形[x0]
                                                                                                             [1]
取(1,1)就是xn了,还要对g取mod.

有个坑点就是爆int ,m非常大,相乘就炸了。
炸了3个点。
最后无奈写了乘法优化,当成二分加法做的。

#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<algorithm>
#include<queue>
#include<iostream>
#include<cmath>
#define LL long long
using namespace std;
const LL maxn=5;
LL m,a,c,x0,n,g;
struct Mat
{
LL mat[maxn][maxn];
Mat()
{
memset(mat,0,sizeof(mat));
}
};
LL cheng(LL x,LL y)
{
LL res=0;
while(y)
{
if(y&1)res=(res+x)%m;
y>>=1;
x=(x+x)%m;
}
return res;
}
Mat operator*(Mat x,Mat y)
{
Mat z;
for(LL k=1;k<=2;k++)
{
for(LL i=1;i<=2;i++)
{
for(LL j=1;j<=2;j++)
{
z.mat[i][j]=(z.mat[i][j]+cheng(x.mat[i][k],y.mat[k][j]))%m;
}
}
}
return z;
}
Mat operator^(Mat x,LL k)
{
Mat z;
for(LL i=1;i<=2;i++)z.mat[i][i]=1;
for(;k;k>>=1)
{
if(k&1)z=z*x;
x=x*x;
}
return z;
}
int main()
{
cin>>m>>a>>c>>x0>>n>>g;
Mat f,h;
f.mat[1][1]=a%m;
f.mat[1][2]=c%m;
f.mat[2][2]=1%m;
h=f^n;
memset(f.mat,0,sizeof(f.mat));
f.mat[1][1]=x0%m;
f.mat[2][1]=1%m;
h=h*f;
cout<<h.mat[1][1]%g<<endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  矩阵乘法 数学