http://acm.hdu.edu.cn/showproblem.php?pid=1757
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.
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
题目解析:
前面已经写了一篇博客如何构造矩阵,这道题可以说就是上片博客的简单应用。
矩阵的乘法不满足交换律,但是却满足结合律,如:A*B*C=A*(B*C);
f(x) = a0 * f(x-1) + a1 * f(x-2) + a2 * f(x-3) + …… + a9 * f(x-10)
构造的矩阵是:
|0 1 0 ......... 0| |f0| |f1 |
|0 0 1 0 ...... 0| |f1| |f2 |
|...................1| * |..| = |...|
|a9 a8 .......a0| |f9| |f10|
然后根据矩阵的结合律,可以先把构造的矩阵的K次幂求出来。最后直接求第一个数。
代码:
加深印象,写了两次。
View Code