问题描述
给定一个N阶矩阵A,输出A的M次幂(M是非负整数) 例如: A = 1 2 3 4 A的2次幂 7 10 15 22
输入格式
第一行是一个正整数N、M(1<=N<=30, 0<=M<=5),表示矩阵A的阶数和要求的幂数 接下来N行,每行N个绝对值不超过10的非负整数,描述矩阵A的值
输出格式
输出共N行,每行N个整数,表示A的M次幂所对应的矩阵。相邻的数之间用一个空格隔开
样例输入
2 2 1 2 3 4
样例输出
7 10 15 22 思路: 由于矩阵都是方阵,所以不需要考虑每次相乘的两个矩阵的顺序,大大降低了题的难度,按照矩阵乘法规则递归调用求解。也可以重载" * ",下面只给出了主要代码。
//#define LOCAL
#include <cstdio>
#include <cstring>
#define MAX_X 30
#define MAX_Y 30
int n, m;
struct Matrix
{
int x, y; //角标
int a[MAX_X][MAX_Y]; //内容
void clear()
{
x = y = 0;
memset(a, 0, sizeof(a));
}
};
void PrintMatrix(Matrix &a, int n)
{
for(int i = 0; i < n; i++)
{
int first = 1;
for(int j = 0; j < n; j++)
{
if(first)
{
printf("%d", a.a[i][j]);
first = 0;
}
else
{
printf(" %d", a.a[i][j]);
}
}
printf("\n");
}
}
Matrix Multiplication(Matrix &a, Matrix &b) //n:阶数 , count:幂 -1
{
Matrix tmp;
tmp.clear(); //初始化矩阵
for(int k = 0; k < n; ++k) //k:积矩阵行
{
for(int x = 0; x < n; ++x)
{
for(int y = 0; y < n; ++y)
{
tmp.a[k][x] += a.a[k][y] * b.a[y][x];
}
}
}
return tmp;
}
int main()
{
#ifdef LOCAL
freopen("input3.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
Matrix a, ans;
scanf("%d", &n);
scanf("%d", &m);
a.x = a.y = n;
for(int i = 0; i < a.x; i++)
{
for(int j = 0; j < a.y; j++)
{
scanf("%d", &a.a[i][j]);
ans.a[i][j] = a.a[i][j];
}
}
if(m == 0)
{
for(int i = 0; i < n; i++)
{
for(int j = 0; j < n; j++)
{
ans.a[i][j] = (i == j) ? 1 : 0;
}
}
}
else
{
for(int i = 0; i < m-1; i++)
{
ans = Multiplication(ans, a);
}
}
PrintMatrix(ans, n);
return 0;
}
struct Matrix
{
int n, m;
int a[MAXN][MAXM];
void clear()
{
n = m = 0;
memset(a, 0, sizeof(a));
}
Matrix operator * (const Matrix &b) const
{
Matrix tmp;
tmp.clear();
tmp.n = n;
tmp.m = b.m;
for(int i = 0; i < n; ++i)
{
for(int j = 0; j< b.m; ++j)
{
for(int k = 0; k < m; ++k)
{
tmp.a[i][j] += a[i][k] * b.a[k][j];
}
}
}
return tmp;
}
};
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有