Matrix Power Series
Time Limit: 3000MS | Memory Limit: 131072K | |
Total Submissions: 24205 | Accepted: 10057 |
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
Source
POJ Monthly--2007.06.03, Huang, Jinsong
题目:给出一个矩阵A,计算A + A^2 + A^3 + ... + A^n。
解题思路:分治,快速模幂。设F(n)= A + A^2 + A^3 + ... + A^n则有F(n)= F(n/2)+ F(n/2)* A^(n/2)+ R(n为奇数存在R,为A^n) = F(n/2){E + A^(n/2)} + R。利用递归和分治求解即可。
#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <queue>
#include <vector>
#include <set>
#include <stack>
#include <map>
#include <climits>
using namespace std;
#define LL long long
const int INF = 0x3f3f3f3f;
struct Matrix
{
int v[41][41];
Matrix()
{
memset(v, 0, sizeof v);
}
}x, p;
int m;
Matrix sum(Matrix a, Matrix b, int n)
{
Matrix c;
for (int i = 0; i<n; i++)
{
for (int j = 0; j<n; j++)
{
c.v[i][j] = a.v[i][j] + b.v[i][j];
c.v[i][j] %= m;
}
}
return c;
}
Matrix mul(Matrix a, Matrix b, int n)
{
Matrix c;
for (int i = 0; i<n; i++)
{
for (int j = 0; j<n; j++)
{
for (int k = 0; k<n; k++)
{
c.v[i][j] += a.v[i][k] * b.v[k][j];
c.v[i][j] %= m;
}
}
}
return c;
}
Matrix pow(Matrix a, int k, int n)
{
Matrix sum = p;
while (k)
{
if (k & 1) sum = mul(sum, a, n);
k >>= 1;
a = mul(a, a, n);
}
return sum;
}
Matrix qpow(Matrix a, int k, int n)
{
if (k == 1) return a;
Matrix b = qpow(a, k / 2, n);
Matrix c = sum(p, pow(a, k / 2, n), n);
if (k % 2) return sum(mul(b, c, n), pow(a, k, n), n);
else return mul(b, c, n);
}
int main()
{
int n, k;
while (~scanf("%d %d %d", &n, &k,&m))
{
for (int i = 0; i<n; i++)
{
for (int j = 0; j<n; j++)
{
scanf("%d", &x.v[i][j]);
x.v[i][j] %= m;
}
}
for (int i = 0; i<n; i++) p.v[i][i] = 1;
Matrix e = x;
Matrix ans = qpow(e, k, n);
for (int i = 0; i<n; i++)
{
for (int j = 0; j<n; j++)
{
printf("%d", ans.v[i][j]);
if (j == n - 1) printf("\n");
else printf(" ");
}
}
}
return 0;
}