1757 A Simple Math Problem 【矩陣快速冪】
A Simple Math ProblemTime Limit: 3000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) Total Submission(s): 6589 Accepted Submission(s): 4045Problem 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. 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. 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 Author linle Source Recommend lcy |
借用一下別人的圖:
直白明瞭,構造好初始的兩個矩陣,然後利用矩陣快速冪即可
#include<bits/stdc++.h>
using namespace std;
#define clr(a) memset(a, 0, sizeof(a))
typedef long long ll;
const int N = 10;
ll k, m;
ll a[N];
struct Matrix{
ll m[N][N];
};
void prin(Matrix x){
for(int i = 0; i < N; i++){
for(int j = 0; j < N; j++){
printf("%lld ", x.m[i][j]);
}
cout << endl;
}
}
Matrix Mul(Matrix a, Matrix b){
Matrix c;
clr(c.m);
for(ll i = 0; i < N; i++)
for(ll j = 0; j < N; j++)
for(ll k = 0; k < N; k++)
c.m[i][j] = (c.m[i][j] + (a.m[i][k]*b.m[k][j]) % m + m) % m;
return c;
}
Matrix fastm(Matrix a, int n){
Matrix res;
clr(res.m);
for(int i = 0; i < N; i++)
res.m[i][i] = 1;
while(n){
if(n & 1) res = Mul(res, a);
n >>= 1;
a = Mul(a, a);
}
return res;
}
int main(){
while(scanf("%lld%lld", &k, &m) != EOF){
for(int i = 0; i < N; i++) scanf("%lld", &a[i]);
Matrix u, v;
clr(u.m); clr(v.m);
for(int i = 0; i < N; i++) u.m[0][i] = a[i];
for(int i = 0; i < N-1; i++) u.m[i+1][i] = 1;
//prin(u);
for(int i = 0; i < N; i++) v.m[10-i-1][0] = i;
//prin(v);
if(k < 10) printf("%lld\n", k);
else{
Matrix fin = fastm(u, k-9);
Matrix ans = Mul(fin, v);
printf("%lld\n", ans.m[0][0] % m);
}
}
return 0;
}