A Simple Math Problem
Problem Description
Lele now is thinking about a simple function f(x).
If x < 10 f(x) = x.
If x >= 10 f(x) = a0 * f(x-1) + a1 * f(x-2) + a2 * f(x-3) + …… + a9 * f(x-10);
And ai(0<=i<=9) can only be 0 or 1 .
Now, I will give a0 ~ a9 and two positive integers k and m ,and could you help Lele to caculate f(k)%m.
If x < 10 f(x) = x.
If x >= 10 f(x) = a0 * f(x-1) + a1 * f(x-2) + a2 * f(x-3) + …… + a9 * f(x-10);
And ai(0<=i<=9) can only be 0 or 1 .
Now, I will give a0 ~ a9 and two positive integers k and m ,and could you help Lele to caculate f(k)%m.
Input
The problem contains mutiple test cases.Please process to the end of file.
In each case, there will be two lines.
In the first line , there are two positive integers k and m. ( k<2*10^9 , m < 10^5 )
In the second line , there are ten integers represent a0 ~ a9.
In each case, there will be two lines.
In the first line , there are two positive integers k and m. ( k<2*10^9 , m < 10^5 )
In the second line , there are ten integers represent a0 ~ a9.
Output
For each case, output f(k) % m in one line.
Sample Input
10 9999
1 1 1 1 1 1 1 1 1 1
20 500
1 0 1 0 1 0 1 0 1 0
Sample Output
45
104
给定公式,求f(k)%m
有公式可得
那么f(x) 就可以得到答案了。
1 #include <bits/stdc++.h> 2 using namespace std; 3 typedef vector<int> vec; 4 typedef vector<vec> mat; 5 int k, m; 6 mat mul(mat &A, mat &B) { 7 mat C(A.size(), vec(B[0].size())); 8 for(int i = 0; i < A.size(); i ++) { 9 for(int j = 0; j < B[0].size(); j ++) { 10 for(int k = 0; k < B.size(); k ++) { 11 C[i][j] = (C[i][j] + A[i][k]*B[k][j]) % m; 12 } 13 } 14 } 15 return C; 16 } 17 mat pow(mat A, int n) { 18 mat B(A.size(), vec(A.size())); 19 for(int i = 0; i < A.size(); i ++) { 20 B[i][i] = 1; 21 } 22 while(n > 0) { 23 if(n&1) B = mul(B, A); 24 A = mul(A, A); 25 n >>= 1; 26 } 27 return B; 28 } 29 int main() { 30 mat A(10,vec(10)); 31 for(int i = 0; i < 9; i ++) { 32 A[i+1][i] = 1; 33 } 34 while(cin >> k >> m) { 35 for(int i = 0; i < 10; i ++) cin >> A[0][i]; 36 if(k < 10) { 37 cout << (k%m) << endl; 38 continue; 39 } 40 mat B = pow(A, k - 9); 41 int ans = 0; 42 for(int i = 0; i < 10; i ++) { 43 ans += (B[0][i]*(9-i))%m; 44 } 45 cout << ans%m << endl; 46 } 47 return 0; 48 }