有一个序列是这样定义的:f(1) = 1, f(2) = 1, f(n) = (A * f(n - 1) + B * f(n - 2)) mod 7.
给出A,B和N,求f(n)的值。
Input
输入3个数:A,B,N。数字之间用空格分割。(-10000 <= A, B <= 10000, 1 <= N <= 10^9)
Output
输出f(n)的值。
Input示例
3 -1 5
Output示例
6
题意:f(n) = (A * f(n - 1) + B * f(n - 2)) mod 7
题解:矩阵快速幂处理
1 1 a 1
*
0 0 b 0
1 #include<iostream> 2 #include<cstring> 3 #include<cstdio> 4 #include<vector> 5 #define ll __int64 6 using namespace std; 7 ll a,b,n; 8 struct matrix 9 { 10 ll m[3][3]; 11 }ans,exm; 12 struct matrix matrix_mlit(struct matrix aa,struct matrix bb) 13 { 14 struct matrix there; 15 for(int i=0;i<2;i++) 16 { 17 for(int j=0;j<2;j++) 18 { 19 there.m[i][j]=0; 20 for(int u=0;u<2;u++) 21 there.m[i][j]=(there.m[i][j]+aa.m[i][u]*bb.m[u][j]%7)%7; 22 } 23 } 24 return there; 25 } 26 ll matrix_quick(ll aa,ll bb,ll gg) 27 { 28 exm.m[0][0]=aa;exm.m[0][1]=1; 29 exm.m[1][0]=bb;exm.m[1][1]=0; 30 ans.m[0][0]=1;ans.m[0][1]=1; 31 ans.m[1][0]=0;ans.m[1][1]=0; 32 gg-=2; 33 while(gg) 34 { 35 if(gg&1) 36 ans=matrix_mlit(ans,exm); 37 exm=matrix_mlit(exm,exm); 38 gg>>=1; 39 } 40 return ans.m[0][0]; 41 } 42 int main() 43 { 44 scanf("%I64d %I64d %I64d",&a,&b,&n); 45 if(n==1){ 46 printf("1 "); 47 return 0; 48 } 49 if(n==2){ 50 printf("1 "); 51 return 0; 52 } 53 printf("%I64d ",(matrix_quick(a,b,n)+7)%7); 54 return 0; 55 }