描述
题解
模版题,矩阵快速幂,但是蓝桥不让带模版,还是自己手打吧!
其实数据范围这么小,普通的矩阵乘法乘 M−1 次就行,完全没必要用矩阵快速幂,非但没有什么效率上的提升,说不定还会慢一些,但是我就是喜欢用矩阵快速幂……
代码
#include <cstdio>
#include <algorithm>
#include <iostream>
using namespace std;
const int MAXN = 33;
int n;
struct mat
{
int m[MAXN][MAXN];
} unit;
mat operator * (mat a, mat b)
{
mat ret;
int x;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
x = 0;
for (int k = 0; k < n; k++)
{
x += a.m[i][k] * b.m[k][j];
}
ret.m[i][j] = x;
}
}
return ret;
}
void init_unit()
{
for (int i = 0; i < MAXN; i++)
{
unit.m[i][i] = 1;
}
}
mat pow_mat(mat a, int n)
{
mat ret = unit;
while (n)
{
if (n & 1)
{
ret = ret * a;
}
n >>= 1;
a = a * a;
}
return ret;
}
int main()
{
int x;
init_unit();
while (cin >> n >> x)
{
mat a;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
cin >> a.m[i][j];
}
}
a = pow_mat(a, x); // a 矩阵的 x 次幂
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (j + 1 == n)
{
cout << a.m[i][j] << endl;
}
else
{
cout << a.m[i][j] << ' ';
}
}
}
}
return 0;
}