Matrix Power Series
Description
Given a n × n matrix A and a positive integer k, find the sum S = A + A2 + A3 + … + Ak.
Input
The input contains exactly one test case. The first line of input contains three positive integers n (n ≤ 30), k (k ≤ 109) and m (m < 104). Then follow n lines each containing n nonnegative integers below 32,768, giving A’s elements in row-major order.
Output
Output the elements of S modulo m in the same way as A is given.
Sample Input
2 2 4
0 1
1 1
Sample Output
1 2
2 3
题意: 计算矩阵A的和, sum = (A + A^2 + A^3 + ... + A^k)%m
解题思路:
1. 式子: sum = A+A^2+A^3+...+A^k
当k是偶数时: 1表示单位矩阵(对角线全为1,其余为0)
sum = (A+A^2+...+A^k)*(1+A^k/2);
当k是奇数时:
sum = (A+A^2+...+A^k/2)*(1+A^k/2+1)+A^k/2+1
2. A^k也是用二分方法求解.
当k是偶数时:
A^k = A^(k/2)*A^(k/2);
当k是奇数时:
A^k = A^(k/2)*A^(k/2)*A;
代码:
#include <cstdio>
#include <iostream>
#include <cstring>
using namespace std;
#define MAX 35
struct matrix
{
int row, column;
int g[MAX][MAX];
};
int n, K, m;
matrix a, temp;
inline matrix matrix_add(matrix A, matrix B, int mod)
{
matrix c;
c.row = c.column = A.row;
for(int i = 0; i < c.row; ++i)
{
for(int j = 0; j < c.column; ++j)
{
c.g[i][j] = (A.g[i][j]+B.g[i][j])%mod;
}
}
return c;
}
inline matrix multiply(matrix A, matrix B, int mod)
{
matrix c;
c.row = A.row;
c.column = B.column;
memset(c.g,0,sizeof(c.g));
for(int i = 0; i < A.row; ++i)
{
for(int k = 0; k < A.column; ++k)
{
if(A.g[i][k] != 0)
{
for(int j = 0; j < B.column; ++j)
{
c.g[i][j] = (c.g[i][j]+A.g[i][k]*B.g[k][j])%mod;
}
}
}
}
return c;
}
matrix matrix_pow(matrix A, int n, int mod)
{
if(n == 1) return a;
matrix t = matrix_pow(A,n/2,mod);
matrix ans = multiply(t,t,mod);
if(n % 2 == 1) ans = multiply(ans,A,mod);
return ans;
}
matrix sum(matrix A, int n, int mod)
{
if(n == 1) return a;
if(n % 2 == 0)
return multiply(sum(A,n/2,mod),matrix_add(temp,matrix_pow(A,n/2,mod),mod),mod);
else
return matrix_add(
multiply(sum(A,n/2,mod),matrix_add(temp,matrix_pow(A,n/2+1,mod),mod),mod),
matrix_pow(A,n/2+1,mod),
mod
);
}
int main()
{
//freopen("input.txt","r",stdin);
while(scanf("%d %d %d",&n, &K, &m) != EOF)
{
temp.row = temp.column = n;
memset(temp.g,0,sizeof(temp.g));
for(int i = 0; i < n; ++i)
temp.g[i][i] = 1;
a.row = a.column = n;
memset(a.g,0,sizeof(a.g));
for(int i = 0; i < n; ++i)
{
for(int j = 0; j < n; ++j)
scanf("%d",&a.g[i][j]);
}
matrix result = sum(a,K,m);
for(int i = 0; i < result.row; ++i)
{
for(int j = 0; j < result.column; ++j)
{
if(j == 0) printf("%d",result.g[i][j]);
else printf(" %d",result.g[i][j]);
}
printf("\n");
}
}
return 0;
}