斐波那契数列(矩阵快速幂)

题意:略

解题说明:

ac代码:

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
ll mod;
struct matrix{
	ll s[2][2];
	int n,m;
	void clear(){
		s[0][0]=1;s[0][1]=1;s[1][0]=1;s[1][1]=0;
		n=2;m=2;
	}
};
matrix mix(matrix A,matrix B){
	matrix re;
	re.n=A.n;re.m=B.m;
	for(int i=0;i<re.n;i++){
	   for(int j=0;j<re.m;j++){
	   	   re.s[i][j]=0;
	   	  for(int k=0;k<A.m;k++){
	   	  	   re.s[i][j]=(re.s[i][j]+(A.s[i][k]*B.s[k][j])%mod)%mod;
			 }
	   } 
	}
	return re; 
}
matrix qpow(matrix A,ll b){
	matrix re;re.n=2;re.m=2;
	re.s[0][0]=1;re.s[0][1]=0;re.s[1][0]=0;re.s[1][1]=1; 
	while(b){
		if(b&1)re=mix(re,A);
		A=mix(A,A);
		b>>=1;
	}
	return re;
}
int main(){
   ll n,m;
   scanf("%lld%lld",&n,&mod);
   if(n==1||n==2){
   	  puts("1");
   	  return 0;
   }
   matrix p,A;
   p.s[0][0]=1;p.s[1][0]=1;
   p.n=1;p.m=1;
   A.clear();
   A=qpow(A,n-2);
   p=mix(A,p);	
   printf("%d",p.s[0][0]);
   return 0;
}


猜你喜欢

转载自blog.csdn.net/zxk_hi/article/details/80301129
今日推荐