codevs1281 Xn数列

时间:2023-03-10 00:56:08
codevs1281 Xn数列
题目描述 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按位相乘可以不要用高精度。

正解:矩阵快速幂+矩阵乘法

解题报告:

  对于一个递推式,求某一项的值。

  这显然是可以矩阵乘法的,用一下快速幂就可以了。但是注意一点,因为对于long long下的乘法很有可能会乘炸,所以我们需要用加法模拟一下乘法(快速幂的形式),就可以啦。

  代码如下:  

  

 //It is made by jump~
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <ctime>
#include <vector>
#include <queue>
#include <map>
#include <set>
using namespace std;
typedef long long LL;
LL MOD,A,C,n,g;
struct matrix{
LL a[][];
}ans,init; inline LL getlong()
{
LL w=,q=; char c=getchar();
while((c<'' || c>'') && c!='-') c=getchar(); if(c=='-') q=,c=getchar();
while (c>='' && c<='') w=w*+c-'', c=getchar(); return q ? -w : w;
} inline LL quick_cj(LL x,LL y){//为防止溢出,用快速幂的方法,用加法代替乘法
LL da=;
while(y>) {
if(y&) da+=x,da%=MOD;
x+=x; x%=MOD;
y>>=;
}
return da;
} inline matrix cj(matrix a,matrix b){
matrix c=init;
for(int i=;i<;i++)
for(int j=;j<;j++)
for(int k=;k<;k++)
c.a[i][j]+=quick_cj(a.a[i][k],b.a[k][j]),c.a[i][j]%=MOD;
return c;
} inline matrix mul(LL x){
matrix base,tmp; tmp=base=init;
tmp.a[][]=; tmp.a[][]=;
base.a[][]=A; base.a[][]=;
base.a[][]=base.a[][]=;
while(x>) {
if(x&) tmp=cj(tmp,base);
base=cj(base,base);
x>>=;
}
return tmp;
} inline void work(){
MOD=getlong(); A=getlong(); C=getlong();
ans.a[][]=getlong(); ans.a[][]=C; n=getlong(); g=getlong();
for(int i=;i<;i++) for(int j=;j<;j++) init.a[i][j]=;
ans=cj(ans,mul(n));
printf("%lld",ans.a[][]%g);
} int main()
{
work();
return ;
}