| Time Limit: 3000MS | Memory Limit: 131072K | |
| Total Submissions: 16403 | Accepted: 6980 |
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
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
int n, m;
struct matrix
{
int m[55][55];
}a;
matrix multiply(matrix x, matrix y)
{
matrix ans;
memset(ans.m, 0, sizeof(ans.m));
for(int i = 1; i <= n; i++)
for(int j = 1; j <= n; j++)
if(x.m[i][j])
for(int k = 1; k <= n; k++)
ans.m[i][k] = (ans.m[i][k] + x.m[i][j] * y.m[j][k]) % m;
return ans;
}
matrix add(matrix x, matrix y)
{
for(int i = 1; i <= n; i++)
for(int j = 1; j <= n; j++)
x.m[i][j] = (x.m[i][j] + y.m[i][j]) % m;
return x;
}
matrix quickmod(matrix a, int p)
{
matrix ans;
memset(ans.m, 0, sizeof(ans.m));
for(int i = 1; i <= n; i++)
ans.m[i][i] = 1;
while(p)
{
if(p & 1)
ans = multiply(ans, a);
p >>= 1;
a = multiply(a, a);
}
return ans;
}
matrix solve(matrix a, int k)
{
if(k == 1)
return a;
matrix ans;
memset(ans.m, 0, sizeof(ans.m));
for(int i = 1; i <= n; i++)
ans.m[i][i] = 1;
ans = add(ans, quickmod(a, k >> 1));
ans = multiply(ans, solve(a, k >> 1));
if(k & 1) //奇数
ans = add(ans, quickmod(a, k));
return ans;
}
int main()
{
int k;
scanf("%d %d %d", &n, &k, &m);
matrix ans, a;
for(int i = 1; i <= n; i++)
for(int j = 1; j <= n; j++)
scanf("%d", &a.m[i][j]);
ans = solve(a, k);
for(int i = 1; i <= n; i++)
{
for(int j = 1; j < n; j++)
printf("%d ", ans.m[i][j]);
printf("%d\n",ans.m[i][n]);
}
}POJ 3233 Matrix Power Series (矩阵快速幂+二分)
原文:http://blog.csdn.net/tc_to_top/article/details/43878231