标签:
Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 3149 Accepted Submission(s): 1323
把斐波那契数列转化为矩阵:
A={1 1}
{1,0};
LL cal(int p,int n){ ///这里是递归求解等比数列模板 1+p+p^2...+p^n if(n==0) return 1; if(n&1){//(1+p+p^2+....+p^(n/2))*(1+p^(n/2+1)); return (1+pow_mod(p,n/2+1))*cal(p,n/2)%mod; } else { //(1+p+p^2+....+p^(n/2-1))*(1+p^(n/2+1))+p^(n/2); return (pow_mod(p,n/2)+(1+pow_mod(p,n/2+1))*cal(p,n/2-1))%mod; } }
#include<stdio.h> #include<iostream> #include<string.h> #include <stdlib.h> #include<math.h> #include<algorithm> using namespace std; typedef long long LL; struct Martix{ LL v[2][2]; }res; LL k,b,n,M; Martix mult(Martix a,Martix b){ Martix temp; for(int i=0;i<2;i++){ for(int j=0;j<2;j++){ temp.v[i][j] = 0; for(int k=0;k<2;k++){ temp.v[i][j] = (temp.v[i][j]+a.v[i][k]*b.v[k][j])%M; } } } return temp; } Martix add(Martix a,Martix b){ for(int i=0;i<2;i++){ for(int j=0;j<2;j++){ a.v[i][j]=(a.v[i][j]+b.v[i][j])%M; } } return a; } Martix pow_mod(Martix a,LL k){ Martix ans; ans.v[0][0]=ans.v[1][1] = 1; ans.v[0][1]= ans.v[1][0]=0; while(k){ if(k&1) ans = mult(ans,a); a=mult(a,a); k>>=1; } return ans; } Martix cal(Martix p,LL k) ///用二分法求矩阵和,递归实现 计算 a^1+a^2.....+a^p { if(k==1) return p; else if(k&1) return add(cal(p,k-1),pow_mod(p,k)); else return mult(cal(p,k>>1),add(pow_mod(p,k>>1),res)); } int main(){ Martix a,t; a.v[0][0] = a.v[0][1] = a.v[1][0] = 1; ///斐波拉契数列的特征值矩阵[1 1 1 0] a.v[1][1] = 0; t.v[0][0] = t.v[1][1] = 1; ///单位矩阵 t.v[0][1] = t.v[1][0] = 0; while(scanf("%lld%lld%lld%lld",&k,&b,&n,&M)!=EOF){ Martix M1 = pow_mod(a,k); res = t; res = add(t,cal(M1,n-1)); if(b!=0){ Martix M3 = pow_mod(a,b); res = mult(res,M3); } printf("%d\n",res.v[0][1]%M); } return 0; }
标签:
原文地址:http://www.cnblogs.com/liyinggang/p/5563186.html