A Simple Math Problem
Time Limit: 3000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 2051 Accepted Submission(s): 1178
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
思路:构造矩阵
|fn| |a0 a1 a2....a9| |fn-1|
|fn-1| |1 0 0.... 0 | |fn-2|
|fn-2| = |0 1 0.... 0| * |fn-3|
...... ..... .....
|fn-9| |0 0 .... 1 0| |fn-10|
AC代码:
#include <iostream>
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <queue>
#include <stack>
#include <ctime>
#include <vector>
#include <algorithm>
#define ll __int64
#define L(rt) (rt<<1)
#define R(rt) (rt<<1|1)
using namespace std;
const int INF = 2000000000;
const int maxn = 10;
struct Mat
{
int mat[maxn][maxn];
void zero()
{
memset(mat, 0, sizeof(mat));
}
void unit()
{
zero();
for(int i = 0; i < maxn; i++) mat[i][i] = 1;
}
}A, T;
int a[10];
int k, m;
Mat operator *(const Mat &a, const Mat &b)
{
Mat tmp;
for(int i = 0; i < maxn; i++)
for(int j = 0; j < maxn; j++)
{
int sum = 0;
for(int k = 0; k < maxn; k++)
sum += a.mat[i][k] * b.mat[k][j];
tmp.mat[i][j] = sum % m;
}
return tmp;
}
Mat operator ^ (Mat x, int n){
Mat tmp;
tmp.unit();
while(n)
{
if(n & 1) tmp = tmp * x;
x = x * x;
n >>= 1;
}
return tmp;
}
void init(){
A.zero();
for(int i = 0; i < maxn; i++)
A.mat[i][0] = maxn - 1 - i;
T.zero();
for(int i = 0; i < maxn; i++)
T.mat[0][i] = a[i];
for(int i = 1; i < maxn; i++)
T.mat[i][i - 1] = 1;
}
int main()
{
while(~scanf("%d%d", &k, &m))
{
for(int i = 0; i < maxn; i++)
scanf("%d", &a[i]);
if(k < 10)
{
printf("%d\n", k);
continue;
}
init();
Mat ans = (T ^ (k - 9)) * A;
printf("%d\n", ans.mat[0][0]);
}
return 0;
}