L1-048. 矩阵A乘以B
给定两个矩阵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
思路:神了,我开始就怀疑了一下这个通过率,果然没这么简单!实例通过后就提交了,但是就给了两分???然后考虑了矩阵等于零的情况,然而还是给了两分?!
好吧,忘记开始忘记输出Ra和Cb了,然后特地试了一下有没有某行或者某列全等于零时,矩阵为零的情况,事实证明这个题目没有要求这一点。
#include<stdio.h> #include<string.h> #include<iostream> using namespace std; int main() { int Ra, Ca, Rb, Cb, a[105][105], b[105][105], c[105][105]; cin >> Ra >> Ca; int flag = 1; for (int i = 1; i <= Ra; i++) for (int j = 1; j <= Ca; j++) cin >> a[i][j]; /*for (int i = 1; i <= Ra; i++) { int cnt = 0; for (int j = 1; j <= Ca; j++) if (a[i][j] == 0)cnt++; if (cnt == Ca)flag = 0; } for (int j = 1; j <= Ca; j++) { int cnt = 0; for (int i = 1; i <= Ra; i++) if (a[i][j] == 0)cnt++; if (cnt == Ra)flag = 0; } */ cin >> Rb >> Cb; for (int i = 1; i <= Rb;i++) for (int j = 1; j <= Cb; j++) cin >> b[i][j]; /*for (int i = 1; i <= Rb; i++) { int cnt = 0; for (int j = 1; j <= Cb; j++) if (b[i][j] == 0)cnt++; if (cnt == Cb)flag = 0; } for (int j = 1; j <= Cb; j++) { int cnt = 0; for (int i = 1; i <= Rb; i++) if (b[i][j] == 0)cnt++; if (cnt == Rb)flag = 0; } */ if (Ca == Rb){ cout << Ra << " " << Cb << endl; //if (flag) { for (int i = 1; i <= Ra; i++) for (int j = 1; j <= Cb; j++) { int sum = 0; for (int p = 1; p <= Ca; p++) sum += a[i][p] * b[p][j]; c[i][j] = sum; } for (int i = 1; i <= Ra; i++) { for (int j = 1; j <= Cb; j++) if (j == 1)cout << c[i][j]; else cout << " " << c[i][j]; cout << endl; } } /*else { for (int i = 1; i <= Ra; i++) { for (int j = 1; j <= Cb; j++) if (j == 1)cout << "0"; else cout << " 0" ; cout << endl; } }*/ } else cout << "Error: " << Ca << " != " << Rb << endl; return 0; }