【SSL 1530】斐波那契数列III【矩阵乘法】

裴波拉契数列III

T i m e Time Time L i m i t : 10000 M S Limit:10000MS Limit:10000MS M e m o r y Memory Memory L i m i t : 65536 K Limit:65536K Limit:65536K
C a s e Case Case T i m e Time Time L i m i t : 1000 M S Limit:1000MS Limit:1000MS

Description

求数列 f [ n ] = f [ n − 1 ] + f [ n − 2 ] + 1 f[n]=f[n-1]+f[n-2]+1 f[n]=f[n1]+f[n2]+1的第 N N N项. f [ 1 ] = 1 , f [ 2 ] = 1 f[1]=1,f[2]=1 f[1]=1,f[2]=1.

Input

n ( 1 < n < 2 31 − 1 ) n(1<n<2^{31-1}) n(1n311)

Output

N N 项的结果 m o d mod mod 9973 9973 9973

Sample Input

12345

Sample Output

8932

分析:

矩阵乘法这个模板类似
同样 考虑矩阵 [ f n − 1 , f n − 2 , 1 ] [f_{n-1},f_{n-2},1] [fn1,fn2,1]
乘上某矩阵 得到
[ f n − 1 , f n , 1 ] = [ f n − 1 , f n − 2 + f n − 1 , 1 ] [f_{n-1},f_n,1]=[f_{n-1},f_{n-2}+f_{n-1},1] [fn1,fn,1]=[fn1,fn2+fn1,1]
容易得出 该矩阵为:
0 , 1 , 0 0,1,0 0,1,0

1 , 1 , 0 1,1,0 1,1,0

0 , 1 , 1 0,1,1 0,1,1
然后直接做矩阵乘法就好了

CODE:

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
const int mod=9973;
long long n;
struct matrix{
    
    
	long long n,m;
	long long G[11][11];
}base,A,B;
matrix operator *(matrix a,matrix b)
{
    
    
	matrix C;
	C.n=a.n;C.m=b.m;
	for(int i=1;i<=C.n;i++)
		for(int j=1;j<=C.m;j++)
			C.G[i][j]=0;
	for(int k=1;k<=a.m;k++)
		for(int i=1;i<=a.n;i++)
			for(int j=1;j<=b.m;j++)
				C.G[i][j]=(C.G[i][j]+a.G[i][k]*b.G[k][j]%mod)%mod;  //矩阵乘法
	return C;
}
void ksm(long long x){
    
    
	if(x==1){
    
    
		A=base;
		return;
	}
	ksm(x/2);
	A=A*A;  //快速幂
	if(x&1) A=A*base;
}
int main(){
    
    
	scanf("%lld",&n);
	base.n=3;base.m=3;
	base.G[1][1]=0;base.G[1][2]=1;base.G[1][3]=0;
	base.G[2][1]=1;base.G[2][2]=1;base.G[2][3]=0;  //乘的矩阵
	base.G[3][1]=0;base.G[3][2]=1;base.G[3][3]=1;
	if(n<=2){
    
    
		printf("1");
		return 0;
	}
	else{
    
    
		B.m=3;B.n=1;
		B.G[1][1]=1;B.G[1][2]=1;B.G[1][3]=1;  //设的矩阵
		ksm(n-1);
		B=B*A;
		printf("%lld",B.G[1][1]);
	}
	
	return 0;
}

猜你喜欢

转载自blog.csdn.net/dgssl_xhy/article/details/111060582
今日推荐