Link:点击打开链接
Description
给定两个矩阵 A A和 B B,你需要判断它们是否可以相乘,若可以请输出相乘后的矩阵。
Input
第一行输入一个整数 T T,代表有 T T组测试数据。
每组数据第一行输入两个整数 N,M N,M,代表矩阵 A A的行、列。
接下来 N N行,每行输入 M M个整数 a[][] a[][]。
之后一行输入两个整数 n,m n,m,代表矩阵 B B的行、列。
接下来 n n行,每行输入 m m个整数 b[][] b[][]。
注: 1<=T<=500,1<=N,m<=100,1<=M,n<=10,1<= 1<=T<=500,1<=N,m<=100,1<=M,n<=10,1<=矩阵元素 <=20 <=20。
Output
若矩阵 A、B A、B可以相乘,先输出 YES YES,再输出相乘得到的矩阵。
对每行的矩阵元素,每两个元素之间有一个空格,最后一个没有空格。
反之输出 NO NO。
Sample Input
2 2 2 1 1 1 1 2 3 1 1 1 1 1 1 2 3 1 1 1 1 1 1 2 2 1 1 1 1
Sample Output
YES 2 2 2 2 2 2 NO
思路:
当第一个矩阵的列数等于第二个矩阵的行数时,可以相乘
Code:
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<iostream>
#include<queue>
#include<stack>
using namespace std;
int a[110][110],b[110][110],c[110][110];
int main()
{
int t,N,M,n,m;
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&N,&M);
for(int i=1;i<=N;i++)
for(int j=1;j<=M;j++)
scanf("%d",&a[i][j]);
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++)
scanf("%d",&b[i][j]);
if(M==n)
{
printf("YES\n");
for(int i=1;i<=N;i++)
for(int j=1;j<=m;j++)
{
c[i][j]=0; //每次都要初始化
for(int k=1;k<=M;k++)
c[i][j]+=a[i][k]*b[k][j];
printf("%d%c",c[i][j],j==m? '\n':' ');
}
}
else
printf("NO\n");
}
return 0;
}