Peaches matrix fast power
total submission: 6 test passed: 3
description
To give a peach recursive, f (n) = 2 * f (n-2) + f (n-1) + n ^ 4, f (1) = a, f (2) = b, now you n, a, b, you to calculate f (n) value of the number.
Entry
A first line integer T (T = 100), expressed T set of data.
For each test, the first row of three integers n (1≤n≤2 ^ 31), a (1≤a≤2 ^ 31), b (1≤b≤2 ^ 31).
Export
For each output data value that is a number f (n), since this number will be large, you need to output value% 2147493647 f (n).
Sample input
Sample Output
prompt
First Example: The third digit 85 = 2 * 1 + 2 + 3 ^ 4.
Second Example: The third digit 93 = 2 * 3 + 1 + 10 ^ 4, the fourth number = 369 2 + 93 + 4 * 10 ^ 4.
Problem-solving ideas:
f [n] = 2 * f [n-2] + f [n-1] + n ^ 4; f [3] = 2 * f [1] + f [2] + 3 ^ 4; How 3 ^ 4 represented by the expression 2
f [n + 1] = 2 * f [n-1] + f [n] + (n + 1) ^ 4; f [4] = 2 * f [2] + f [3] + 4 * 4; 4 ^ 4 how represented by the expression of 4d
(N + 1) ^ 4 = n ^ 4 + 4 * n ^ 3 + 6 * n ^ 2 + 4 * n + 1; // After a one represented by the first
Therefore, initial matrix ba 16 8 4 2 1
The configuration of the code matrix
1 #include <bits/stdc++.h> 2 #define ll long long 3 #define mod(x) ((x)%MOD) 4 using namespace std; 5 6 int t; 7 const ll MOD=2147493647; 8 const int maxn=7; 9 ll n,A,B; 10 11 struct mat{ 12 int m[maxn][maxn]; 13 }unit; 14 15 mat operator*(mat a,mat b){ 16 mat ret; 17 ll x=0; 18 for(int i=0;i<maxn;i++) 19 for(int j=0;j<maxn;j++){ 20 x=0; 21 for(int k=0;k<maxn;k++){ 22 x+=mod(1LL*a.m[i][k]*b.m[k][j]); 23 } 24 ret.m[i][j]=mod(x); 25 } 26 return ret; 27 } 28 29 void init_unit(){ 30 for(int i=0;i<maxn;i++){ 31 unit.m[i][i]=1; 32 } 33 return; 34 } 35 36 mat pow_mat(mat a,ll m){ 37 mat ret=unit; 38 while(m){ 39 if(m&1) ret=ret*a; 40 a=a*a; 41 m>>=1; 42 } 43 return ret; 44 45 } 46 47 int main(){ 48 ios::sync_with_stdio(false); 49 init_unit(); 50 cin>>t; 51 while(t--){ 52 cin>>n>>A>>B; 53 mat a,b; 54 if(n==1) cout << A << endl; 55 else if(n==2) cout << B << endl; 56 else{ 57 a.m[0][0]=B,a.m[0][1]=A,a.m[0][2]=16,a.m[0][3]=8,a.m[0][4]=4,a.m[0][5]=2,a.m[0][6]=1; 58 59 b.m[0][0]=1,b.m[0][1]=1,b.m[0][2]=0,b.m[0][3]=0,b.m[0][4]=0,b.m[0][5]=0,b.m[0][6]=0; 60 b.m[1][0]=2,b.m[1][1]=0,b.m[1][2]=0,b.m[1][3]=0,b.m[1][4]=0,b.m[1][5]=0,b.m[1][6]=0; 61 b.m[2][0]=1,b.m[2][1]=0,b.m[2][2]=1,b.m[2][3]=0,b.m[2][4]=0,b.m[2][5]=0,b.m[2][6]=0; 62 b.m[3][0]=4,b.m[3][1]=0,b.m[3][2]=4,b.m[3][3]=1,b.m[3][4]=0,b.m[3][5]=0,b.m[3][6]=0; 63 b.m[4][0]=6,b.m[4][1]=0,b.m[4][2]=6,b.m[4][3]=3,b.m[4][4]=1,b.m[4][5]=0,b.m[4][6]=0; 64 b.m[5][0]=4,b.m[5][1]=0,b.m[5][2]=4,b.m[5][3]=3,b.m[5][4]=2,b.m[5][5]=1,b.m[5][6]=0; 65 b.m[6][0]=1,b.m[6][1]=0,b.m[6][2]=1,b.m[6][3]=1,b.m[6][4]=1,b.m[6][5]=1,b.m[6][6]=1; 66 67 b=pow_mat(b,n-2); 68 a=a*b; 69 cout << a.m[0][0] << endl; 70 } 71 } 72 return 0; 73 }