【矩阵相乘】【SSL 1531】 斐波拉契数列IV

【矩阵相乘】【SSL 1531】 斐波拉契数列IV

题目

求数列f[n]=f[n-2]+f[n-1]+n+1的第N项,其中f[1]=1,f[2]:=1.


输入

N(1<N<2^31-1)


输出

第n项结果 mod 9973


样例

input
10000

output
4399


解题思路

相乘矩阵长这样
在这里插入图片描述


代码

#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
const int mo=9973;
struct lzf{
    
    
	long long n,m,h[10][10];
}a,b,x;
long long n;
lzf operator *(lzf l,lzf y)
{
    
    
	x.n=l.n,x.m=y.m;
	memset(x.h,0,sizeof(x.h));
	for (int k=1;k<=l.m;k++)
	    for (int i=1;i<=x.n;i++)
	        for (int j=1;j<=x.m;j++)
	            x.h[i][j]=(x.h[i][j]+l.h[i][k]*y.h[k][j]%mo)%mo;
	return x;
}
void power(long long n)
{
    
     
	 if (n & 1) a=a*b;
	 if (n==1) return;
	 b=b*b;
	 power(n/2);
}
int main()
{
    
    
	a.n=1,a.m=4;
	a.h[1][1]=a.h[1][2]=a.h[1][4]=1;
	a.h[1][3]=3; 
	b.n=4,b.m=4;
	b.h[1][2]=b.h[2][1]=b.h[2][2]=b.h[3][2]=1;
	b.h[3][3]=b.h[4][2]=b.h[4][3]=b.h[4][4]=1;
	scanf("%lld",&n);
	power(n-1);
    printf("%lld",a.h[1][1]);	
} 

猜你喜欢

转载自blog.csdn.net/qq_45621109/article/details/111402037