蓝桥杯 BASIC 27 矩阵乘法(矩阵、二维数组)

时间:2023-03-09 21:21:35
蓝桥杯 BASIC 27 矩阵乘法(矩阵、二维数组)

【思路】:注意0次幂是单位矩阵。

【AC代码】:

#include <iostream>
#include <algorithm>
#include <iomanip>
#include <cstdio>
#include <cstring>
using namespace std; #define MAX 30+2 void cal(int m[MAX][MAX], int t[MAX][MAX], int r[MAX][MAX], int N)
{
int i = 0, j = 0, k = 0;
for (i = 0; i < N; i++)
{
for (j = 0; j < N; j++)
{
int temp = 0;
for (k = 0; k < N; k++)
{
temp += m[i][k] * t[k][j];
}
r[i][j] = temp;
}
}
} void copy(int t[MAX][MAX], int r[MAX][MAX], int N)
{
int i = 0, j = 0;
for (i = 0; i < N; i++)
{
for (j = 0; j < N; j++)
{
t[i][j] = r[i][j];
}
}
} int main()
{
//freopen("in.txt", "r", stdin);
//freopen("out.txt", "w", stdout);
int N = 0, M = 0, matrix[MAX][MAX], temp[MAX][MAX], res[MAX][MAX];
int i = 0, j = 0; //input
cin >> N >> M;
for (i = 0; i < N; i++)
{
for (j = 0; j < N; j++)
{
cin >> matrix[i][j];
if (i == j)
{
temp[i][j] = 1;
res[i][j] = 1;
}
else
{
temp[i][j] = 0;
res[i][j] = 0;
}
}
} //cal
for (i = 0; i < M; i++)
{
cal(matrix, temp, res, N);
copy(temp, res, N);
} for (i = 0; i < N; i++)
{
for (j = 0; j < N; j++)
{
cout << res[i][j] << " ";
}
cout << endl;
}
return 0;
}