标签:
题目大意:Given a n × n matrix A and a positive integer k, find the sum S = A + A^2 + A^3 + … + A^k.
解题思路:将矩阵分块就可以解决了,
其中的S表示的是前n项的和,An指的是A^n, E指单位阵,O指零矩阵
#include<cstdio>
typedef long long ll;
const int N = 65;
struct Matrix {
ll mat[N][N];
}A, B, tmp, C, Ans;
ll n, K, m;
Matrix matMul(Matrix x, Matrix y) {
for(int i = 0; i < 2 * n; i++)
for(int j = 0; j < 2 * n; j++) {
tmp.mat[i][j] = 0;
for(int k = 0; k < 2 * n; k++)
tmp.mat[i][j] += (x.mat[i][k] * y.mat[k][j]) % m;
}
return tmp;
}
void solve() {
while(K) {
if(K & 1)
B = matMul(B,A);
A = matMul(A,A);
K >>= 1;
}
}
void init() {
for(int i = 0; i < 2 * n; i++)
for(int j = 0; j < 2 * n; j++) {
B.mat[i][j] = 0;
if(i == j)
B.mat[i][j] = 1;
}
for(int i = 0; i < n; i++)
for(int j = 0; j < 2 * n; j++) {
A.mat[i][j] = 0;
if(i == j)
A.mat[i][j] = 1;
}
}
void solve2() {
for(int i = 0; i < n; i++)
for(int j = 0; j < n; j++) {
Ans.mat[i][j] = 0;
for(int k = 0; k < 2 * n; k++)
Ans.mat[i][j] += (C.mat[i][k] * B.mat[k][j]) % m;
}
}
int main() {
while(scanf("%I64d%I64d%I64d", &n, &K, &m) != EOF) {
for(int i = 0; i < n; i++)
for(int j = 0; j < n; j++) {
scanf("%lld", &A.mat[i+n][j]);
C.mat[i][j] = C.mat[i][j+n] = A.mat[i+n][j+n] = A.mat[i+n][j];
}
if(K == 1) {
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
if(j)
printf(" ");
printf("%I64d", A.mat[i+n][j]);
}
printf("\n");
}
continue;
}
init();
K--;
solve();
solve2();
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
if(j)
printf(" ");
printf("%I64d", Ans.mat[i][j] % m);
}
printf("\n");
}
}
return 0;
}
POJ - 3233 Matrix Power Series 矩阵快速幂
标签:
原文地址:http://blog.csdn.net/l123012013048/article/details/46117253