PTA_L1-048 matrix A is multiplied by B (15 minutes)

L1-048 matrix A is multiplied by B

Given two matrices A and B, they require you to calculate the matrix product AB. It should be noted that the matrix can be multiplied only the size of a match. That is, if there are A row R a, C a row, B row have a R b, C b columns, only equal to C a R b, two matrices can be multiplied.

Input format:
input has given two matrices A and B. For each matrix, which is given first in the row number of rows R and columns C, then R rows of C are given integers, separated by a space, and the row end to end extra spaces. Ensure two input matrices R and C are positive, and the absolute value of all integers not more than 100.

Output format:
If the size of the two input matrices are matched, according to the input format of the output matrix product AB, otherwise the output Error:! Ca = Rb, where column A is the number of Ca, Rb is the number of rows of B.

Sample Input 1:

2 3
1 2 3
4 5 6
3 4
7 8 9 0
-1 -2 -3 -4
5 6 7 8

Output Sample 1:

2 4
20 22 24 16
53 58 63 28

Sample Input 2:

3 2
38 26
43 -5
0 17
3 2
-11 57
99 68
81 72

Output Sample 2:

Error: 2 != 3

Ideas: understand matrix multiplication.

Complete code:

#include<bits/stdc++.h>
using namespace std;
int a[110][110];
int b[110][110];
int c[110][110];
int main()
{
    int Ra,Ca,Rb,Cb;
    cin>>Ra>>Ca;
    for(int i=0;i<Ra;i++)
    {
        for(int j=0;j<Ca;j++)
        {
            cin>>a[i][j];
        }
    }
    cin>>Rb>>Cb;
    for(int i=0;i<Rb;i++)
    {
        for(int j=0;j<Cb;j++)
        {
            cin>>b[i][j];
        }
    }
    if(Ca!=Rb)
    {
        printf("Error: %d != %d\n",Ca,Rb);
    }
    else
    {
        cout<<Ra<<" "<<Cb<<endl;
        //矩阵乘法
        for(int i=0;i<Ra;i++)
        {
            for(int j=0;j<Cb;j++)
            {
                for(int k=0;k<Ca;k++)
                {
                    c[i][j]+=a[i][k]*b[k][j];
                }
            }
        }
        for(int i=0;i<Ra;i++)
        {
            for(int j=0;j<Cb;j++)
            {
                if(j!=Cb-1)
                {
                    cout<<c[i][j]<<" ";
                }
                else
                {
                    cout<<c[i][j]<<endl;
                }
            }
        }
    }
    return 0;
}

Link to the original question:
https://pintia.cn/problem-sets/994805046380707840/problems/994805082313310208

Published 87 original articles · 98 won praise · views 4947

Guess you like

Origin blog.csdn.net/qq_45856289/article/details/104884280