The sum of the first n items [matrix multiplication]

Time Limit:1000MS Memory Limit:65536K
Total Submit:53 Accepted:41


Description

Find the sequence f [n] = f [n − 1] + f [n − 2] + n + 1, f [1] = f [2] = 1 f[n]=f[n-1]+f[ n-2]+n+1,f[1]=f[2]=1f[n]=f[n1]+f[n2]+n+1,f[1]=f[2]=The sum of the first n items of 1 s [n] s[n]s[n]


Input

N ( 1 < N < 2 3 1 − 1 ) N(1<N<2^31-1) N(2311)

Output

Nth result


Sample Input

100

Sample Output

2528


Source

elba


Problem solving ideas

Matrix multiplication

Consider a 1×5 matrix [f [n − 2], f [n − 1], s [n − 2], n, 1] [f[n-2],f[n-1],s[n -2],n,1】f[n2],f[n1],s[n2],n,1 ] ,
we need to find a 5×5 matrix A, and multiply it by A to get the following 1×5 matrix:
[f [n − 1], f [n], s [n − 1], n + 1 , 1] = [f [n − 1], f [n − 1] + f [n − 2] + n + 1, s [n − 2] + f [n − 1], n + 1, 1] [F[n-1],f[n],s[n-1],n+1,1] =[f[n-1], f[n-1]+f[n-2]+n +1,s[n-2]+f[n-1],n+1,1】f[n1],f[n],s[n1],n+1,1=f[n1],f[n1]+f[n2]+n+1,s[n2]+f[n1],n+1,1 ] It is
easy to construct A as:
Insert picture description here


Code

#include<algorithm>
#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
const int INF=9973;
long long n;
using namespace std;
struct c{
    
    
	int n,m;
	int a[10][10];
}A,B,CC;
c operator *(c A,c B){
    
    
	c 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.a[i][j]=0;
	for(int k=1;k<=A.m;k++)
	{
    
    
		for(int i=1;i<=C.n;i++)
			for(int j=1;j<=C.m;j++)
				C.a[i][j]=(C.a[i][j]+(A.a[i][k]*B.a[k][j])%INF)%INF;
	}	
	return C;
}
void poww(long long x){
    
    
	if(x==1)
	{
    
    
		B=A;
		return; 
	}
	poww(x>>1);
	B=B*B;
	if(x&1)
		B=B*A;
	
}
int main(){
    
    
	scanf("%lld",&n);
	if(n==1){
    
    
		printf("1");
		return 0;
	}
	A.n=5,A.m=5;
	A.a[1][1]=0,A.a[1][2]=1,A.a[1][3]=0,A.a[1][4]=0,A.a[1][5]=0;
	A.a[2][1]=1,A.a[2][2]=1,A.a[2][3]=0,A.a[2][4]=0,A.a[2][5]=1;
	A.a[3][1]=0,A.a[3][2]=1,A.a[3][3]=1,A.a[3][4]=0,A.a[3][5]=0;
	A.a[4][1]=0,A.a[4][2]=1,A.a[4][3]=1,A.a[4][4]=1,A.a[4][5]=0;
	A.a[5][1]=0,A.a[5][2]=0,A.a[5][3]=0,A.a[5][4]=0,A.a[5][5]=1;
	poww(n-1);
	CC.n=1,CC.m=5;
	CC.a[1][1]=1,CC.a[1][2]=1,CC.a[1][3]=3,CC.a[1][4]=1,CC.a[1][5]=1;
	CC=CC*B;
	printf("%d\n",CC.a[1][5]);
	
}

Guess you like

Origin blog.csdn.net/kejin2019/article/details/111063562