这是我矩阵快速幂入门的最后一练,从了解矩阵快速幂,到现在应用,其实矩阵快速幂可以分为两点,一点是矩阵的相乘,另外一点就是快速幂的掌握,所以并不需要把矩阵快速幂的代码实现想象的很困难。但是这并不是说矩阵快速幂的应用不难,通过这题,可以感受到,矩阵快速幂的应用,重点是要找到递推关系,然后将状态转移矩阵构建出来,这个是最关键的。初始矩阵不同,所构建的状态转移矩阵肯定也会不同。
In our daily life we often use 233 to express our feelings. Actually, we may say 2333, 23333, or 233333 ... in the same meaning. And here is the question: Suppose we have a matrix called 233 matrix. In the first line, it would be 233, 2333, 23333... (it means a 0,1 = 233,a 0,2 = 2333,a 0,3 = 23333...) Besides, in 233 matrix, we got a i,j = a i-1,j +a i,j-1( i,j ≠ 0). Now you have known a 1,0,a2,0,...,a n,0, could you tell me a n,m in the 233 matrix?
Input
There are multiple test cases. Please process till EOF.
For each case, the first line contains two postive integers n,m(n ≤ 10,m ≤ 109). The second line contains n integers, a 1,0,a 2,0,...,a n,0(0 ≤ a i,0 < 2 31).
Output
For each case, output a n,m mod 10000007.
Sample Input
1 1 1 2 2 0 0 3 7 23 47 16
Sample Output
234 2799 72937
题意分析:根据题目所描述的问题矩阵,先知分析第一列和第二列,第一列是输入的一列值,第二列的第一行值已经给出是233,那么根据递推关系,可以通过第一列的值和233将第2列的所有空缺的值递推出来,第二列的值推出来后,可以将第三列的值推出来,以此类推,就把问题矩阵的所有值推导了出来。然后分析发现其实a(n,m)的值就是m-1列1~(n-1)项的值与第m列第一个值相加的结果。
得到状态转移矩阵和初始矩阵,初始状态矩阵的构建可以根据个人来定,这是我构建的初始矩阵。
由于数据非常大,要记得取模,同时对于矩阵的大小也一定要跟随自己构建的矩阵来定。
代码如下:
#include
#include
#define ll long long
using namespace std;
const ll Mod = 10000007;
ll N, M;
struct Matrix
{
ll m[13][13];
};
Matrix multi(Matrix a, Matrix b)
{
Matrix ans;
memset(ans.m, 0, sizeof(ans.m));
for(int i = 1; i <= N; i++)
for(int j = 1; j <= N; j++)
for(int k = 1; k <= N; k++)
ans.m[i][j] = (ans.m[i][j] + a.m[i][k]*b.m[k][j] % Mod) % Mod;
return ans;
}
Matrix pow(Matrix a, ll n)
{
Matrix ans;
memset(ans.m, 0, sizeof(ans.m));
for(int i = 1; i <= N; i++)
ans.m[i][i] = 1;
while(n)
{
if(n&1)
ans = multi(ans, a);
n >>= 1;
a = multi(a, a);
}
return ans;
}
int main()
{
Matrix ans, res;
while(cin >> N >> M)
{
if(N==0)
{
M++;
}
Matrix temp;
memset(ans.m, 0, sizeof(ans.m));
memset(res.m, 0, sizeof(res.m));
for(int i =1; i <= N+1; i++)
{
res.m[i][1] = 10, res.m[i][N+2]=1;
for(int j = 2; j <= i; j++)
{
res.m[i][j] = 1;
}
}
res.m[N+2][N+2] = 1;
ans.m[1][1] = 23, ans.m[N+2][1] = 3;
for(int i = 2; i <= N+1; i ++)
cin >> ans.m[i][1];
N = N+2;
temp = pow(res, M);
ans = multi(temp, ans);
cout << ans.m[N-1][1] << endl;
}
return 0;
}