L1-048 矩阵A乘以B

题目 L1-048 矩阵A乘以B

image-5a84fb37

思路分析

代码实现

#include<bits/stdc++.h>

using namespace std;

#define endl '\n'

using ll = long long;

using ull = unsigned long long;

using PII = pair<int,int>;

using Pll = pair<ll,ll>;

int dx[4]= {-1,0,1,0},dy[4]= {0,1,0,-1};

const int inf = 0x3f3f3f3f;

// A 有Ra行 Ca列

// B 有Rb行 Cb列

// 只有Ca==Rb时才能相乘

// 矩阵相乘方法:

// 第一个矩阵第i行上的n个数

// 与第二个矩阵第j列上的n个数

// 对应相乘

// 后所得的n个乘积之和为第i行第j列位置上的数。

// 1 2 3

// 4 5 6

// 7 8 9 0

// -1 -2 -3 -4

// 5 6 7 8

// 1*7 + 2*(-1) + 3*5 = 20

// 1*8 + (-2)*2 + 3*6 = 22

// 4*7 + 5*(-1) + 6*5 = 53

// 20 22 ……

// 53

int main() {

	ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);

	int x1,y1,x2,y2;

	cin>>x1>>y1;

	int a1[x1][y1];

	for(int i=0; i<x1; i++) {

		for(int j=0; j<y1; j++) {

			cin>>a1[i][j];

		}

	}

	cin>>x2>>y2;

	int a2[x2][y2];

	for(int i=0; i<x2; i++) {

		for(int j=0; j<y2; j++) {

			cin>>a2[i][j];

		}

	}

	if(x2!=y1) {

		cout<<"Error: "<<y1<<" != "<<x2<<endl;

	} else {

		cout<<x1<<" "<<y2<<endl;

		for(int i=0; i<x1; i++) {

			for(int j=0; j<y2; j++) {

				int sum=0;

				for(int z=0; z<x2; z++) {

					sum+=a1[i][z]*a2[z][j];

				}

				cout<<sum;

				if(j!=y2-1)	cout<<" ";

				if(j==y2-1 && i!=x1-1)	cout<<endl;

			}

		}

	}

	return 0;

}

同类题型

视频讲解


⬅️ L1-047 装睡 🏠 00-天梯赛 ➡️ L1-049 天梯赛座位分配