给定两个矩阵A和B,要求你计算它们的乘积矩阵AB。需要注意的是,只有规模匹配的矩阵才可以相乘。即若A有Ra 行、Ca 列,B有Rb 行、Cb 列,则只有Ca与Rb相等时,两个矩阵才能相乘。
输入格式:
输入先后给出两个矩阵A和B。对于每个矩阵,首先在一行中给出其行数R和列数C,随后R行,每行给出C个整数,以1个空格分隔,且行首尾没有多余的空格。输入保证两个矩阵的R和C都是正数,并且所有整数的绝对值不超过100。
输出格式:
若输入的两个矩阵的规模是匹配的,则按照输入的格式输出乘积矩阵AB,否则输出Error: Ca != Rb,其中Ca是A的列数,Rb是B的行数。
输入样例1:
2 3
1 2 3
4 5 6
3 4
7 8 9 0
-1 -2 -3 -4
5 6 7 8
输出样例1:
2 4
20 22 24 16
53 58 63 28
输入样例2:
3 2
38 26
43 -5
0 17
3 2
-11 57
99 68
81 72
输出样例2:
Error: 2 != 3
#include<bits/stdc++.h>
#include<unordered_map>
using namespace std;
typedef long long ll;
const int inf=0x3f3f3f3f;
const int maxn=5001;
int a[maxn][maxn],b[maxn][maxn],c[maxn][maxn];
int main()
{
int n,m,x,y;
cin>>n>>m;
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++)
cin>>a[i][j];
cin>>x>>y;
for(int i=1;i<=x;i++)
for(int j=1;j<=y;j++)
cin>>b[i][j];
if(m!=x)
{
cout<<"Error: "<<m<<" != "<<x<<endl;
return 0;
}
cout<<n<<" "<<y<<endl;
for(int i=1;i<=n;i++)
for(int j=1;j<=y;j++)
{
int res=0;
for(int k=1;k<=m;k++)
{
res+=a[i][k]*b[k][j];
}
if(j!=y)
cout<<res<<" ";
else cout<<res<<endl;
}
system("pause");
return 0;
}