题意:给出矩阵,求前k次方和
A^1+A^2+A^3+......A^n=(E+A^(n/2))*(A^1+A^2+.....A^(n/2))
一个式子解决
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#define rep(i, j, k) for(int i = j; i <= k; i++)
using namespace std;
int n;
struct matrix
{
int a[45][45];
}zero, e, a;
matrix operator + (matrix x, matrix y)
{
matrix ret = zero;
rep (i, 1, n)
rep (j, 1, n)
ret.a[i][j] = (x.a[i][j] + y.a[i][j]) % 10;
return ret;
}
matrix operator * (matrix x, matrix y)
{
matrix ret = zero;
rep (i, 1, n)
rep (j, 1, n)
rep (k, 1, n)
ret.a[i][j] += x.a[i][k] * y.a[k][j], ret.a[i][j] %= 10;
return ret;
}
matrix power (matrix x, int p)
{
if (p == 0)
return e;
matrix ret = power (x, p / 2);
if (p % 2)
return x * ret * ret;
return ret * ret;
}
matrix pow (matrix x, int p)
{
if (p == 0)
return zero;
int t = p / 2;
matrix last = pow (x, t);
last = (e + power (x, t)) * last;
if (p % 2)
return last + power (x, p);
return last;
}
int main ()
{
int m;
while (scanf ("%d%d", &n, &m) == 2 && n)
{
rep (i, 1, n)
rep (j, 1, n)
scanf ("%d", &a.a[i][j]), a.a[i][j] %= 10;
rep (i, 1, n)
rep (j, 1, n)
e.a[i][j] = i == j ? 1 : 0;
rep (i, 1, n)
rep (j, 1, n)
zero.a[i][j] = 0;
matrix ans = pow (a, m);
for (int i = 1; i <= n; i++, printf ("\n"))
{
rep (j, 1, n - 1)
printf ("%d ", ans.a[i][j] % 10);
printf ("%d", ans.a[i][n] % 10);
}
printf ("\n");
}
return 0;
}