藍橋9.26-3

Kokonuts發表於2020-09-26

BASIC-17 VIP試題 矩陣乘法

暴力就完事了

const int maxn = 1e2 + 5;
int a[maxn][maxn], b[maxn][maxn], ans[maxn][maxn];
int main()
{
	ios::sync_with_stdio(false);
	//freopen("in.txt", "r", stdin);
	//freopen("out.txt", "w", stdout);
	int n, m;
	cin >> n >> m;
	for (int i = 0; i < n; i++)
		for (int j = 0; j < n; j++)
		{
			cin >> a[i][j];
			b[i][j] = ans[i][j] = a[i][j];
		}
	if (m == 0)
	{
		for (int i = 0; i < n; i++)
		{
			for (int j = 0; j < n; j++)
			{
				if (j) cout << " ";
				cout << 1;
			}
			cout << endl;
		}
	}
	else
	{
		for (int cnt = 1; cnt <= m - 1; cnt++)
		{
			memset(ans, 0, sizeof(ans));
			for (int i = 0; i < n; i++)
				for (int j = 0; j < n; j++)
					for (int k = 0; k < n; k++)
						ans[i][j] += a[i][k] * b[k][j];
			for (int i = 0; i < n; i++)
				for (int j = 0; j < n; j++)
					a[i][j] = ans[i][j];
		}
		for (int i = 0; i < n; i++)
		{
			for (int j = 0; j < n; j++)
			{
				if (j) cout << " ";
				cout << ans[i][j];
			}
			cout << endl;
		}
	}
	return 0;
}