其中 f(1)=x0,f(2)=y0, f( i )=f( i-1 )+f( i+1 ),求 f(n)

 

#include <iostream>
 #include <cmath>
 #include <algorithm>
 using namespace std; 
 #define N 2
  int mod=1e9+7;
 
 #define int long long
  struct matrix {
  	int a[N+2][N+2];
  };
  int n;
  matrix m1; 
  
  void init_e(matrix &x){
  	
  	int i,j;
  	for(i=1;i<=N;i++)
  	 for(j=1;j<=N;j++) {
  	 	 x.a[i][j]=0;
  	 	 if(i==j) x.a[i][j]=1;
  	 }
  }
  matrix mul(matrix &x,matrix &y){
 	int i,j,k;
 	matrix z;
 	
 	for(i=1;i<=N;i++)
 	 for(j=1;j<=N;j++){
 	 	z.a[i][j]=0;
 	 	for(k=1;k<=N;k++)
 	 	 z.a[i][j]+=x.a[i][k]*y.a[k][j], z.a[i][j]%=mod;
 	 }
 	
 	return z;
 }
   matrix ksm(matrix &x,int k){
 	matrix tmp=x, ans;
 	init_e(ans);
 	
 	while(k){
 		if(k&1) ans=mul(ans,tmp);
 		
 		tmp=mul(tmp,tmp); 
 		k/=2;
 	}
 	return ans;
 }
 
  signed main(){
 	std::ios::sync_with_stdio(0);
 	int x0,y0; 
 	cin>>x0>>y0>>n;
 	if(n==1){ cout<<(x0%mod+mod)%mod<<endl; return 0; }
 	
	 	m1.a[1][1]=1,m1.a[1][2]= -1;
	 	m1.a[2][1]=1,m1.a[2][2]= 0;
	 	
	 	matrix ans =ksm(m1,n-2);
	 	cout<< ((ans.a[1][1]*y0+ans.a[1][2]*x0)%mod+mod)%mod<<endl;
	 	cout<<endl;
  }	
 
 

 

posted on 2023-02-26 15:34  towboat  阅读(14)  评论(0)    收藏  举报