Jzzhu has invented a kind of sequences, they meet the following property:
You are given x and y, please calculate fn modulo 1000000007 (109?+?7).
Input
The first line contains two integers x and y (|x|,?|y|?≤?109). The second line contains a single integer n (1?≤?n?≤?2·109).
Output
Output a single integer representing fn modulo 1000000007 (109?+?7).
Examples
Input
2 33
Output
1
Input
0 -12
Output
1000000006
Note
In the first sample, f2?=?f1?+?f3, 3?=?2?+?f3, f3?=?1.
In the second sample, f2?=??-?1; ?-?1 modulo (109?+?7) equals (109?+?6).
AC代码:
1 #include<iostream> 2 #include<cstring> 3 #include<cstdio> 4 using namespace std; 5 struct matrix{ 6 long long int mat[3][3]; 7 }A,B; 8 long long int mod(long long int n){ 9 if(n > 0) 10 return n % 1000000007; 11 else if(n < 0) 12 return (n + 1000000007) % 1000000007; 13 else 14 return 0; 15 } 16 matrix mul(matrix a,matrix b){ 17 matrix tmp; 18 memset(tmp.mat,0,sizeof(tmp.mat)); 19 for(int i = 0;i < 3;i++) 20 for(int j = 0;j < 3;j++) 21 for(int k = 0;k < 3;k++){ 22 tmp.mat[i][j] += a.mat[i][k] * b.mat[k][j]; 23 tmp.mat[i][j] = mod(tmp.mat[i][j]); 24 } 25 return tmp; 26 } 27 matrix pow_mat(matrix a,int n){ 28 matrix ans; 29 memset(ans.mat,0,sizeof(ans.mat)); 30 for(int i = 0;i < 3;i++) 31 ans.mat[i][i] = 1; 32 while(n){ 33 if(n & 1) 34 ans = mul(ans,a); 35 a = mul(a,a); 36 n >>= 1; 37 } 38 return ans; 39 } 40 int main(){ 41 long long int x,y,n; 42 scanf("%lld%lld%lld",&x,&y,&n); 43 if(n == 1) 44 printf("%lld\n",mod(x)); 45 else if(n == 2) 46 printf("%lld\n",mod(y)); 47 else if(n == 3) 48 printf("%lld\n",mod(y - x + 1000000007)); //注意这里的取模 49 else{ 50 A.mat[0][0] = x,A.mat[0][1] = y,A.mat[0][2] = y - x; 51 B.mat[0][0] = 0,B.mat[0][1] = 0,B.mat[0][2] = 0; 52 B.mat[1][0] = 1,B.mat[1][1] = 0,B.mat[1][2] = -1; 53 B.mat[2][0] = 0,B.mat[2][1] = 1,B.mat[2][2] = 1; 54 B = pow_mat(B,n - 3); 55 printf("%lld\n",mod(mul(A,B).mat[0][2])); 56 } 57 return 0; 58 }
原文地址:https://www.cnblogs.com/Luckykid/p/9740329.html
时间: 2024-10-15 05:36:12