L1-048 矩阵A乘以B(Java、C)团体程序设计天梯赛-练习集

给定两个矩阵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


Java版本,最后一个测试点超时:

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        int Ra = scanner.nextInt();
        int Ca = scanner.nextInt();
        int[][] A = new int[Ra][Ca];

        // input matrixA
        for (int i = 0; i < Ra; i++) {
            for (int j = 0; j < Ca; j++) {
                A[i][j] = scanner.nextInt();
            }
        }

        int Rb = scanner.nextInt();

        if (Ca == Rb) {
            int Cb = scanner.nextInt();
            int[][] B = new int[Rb][Cb];

            // input matrixB
            for (int i = 0; i < Rb; i++) {
                for (int j = 0; j < Cb; j++) {
                    B[i][j] = scanner.nextInt();
                }
            }

            System.out.println(Ra + " " + Cb);
            int[][] C = new int[Ra][Cb];

            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];
                    }
                    System.out.print(C[i][j]);

                    if (j != Cb-1) {
                        System.out.print(" ");
                    }
                }
                System.out.println();
            }

        } else {
            System.out.println("Error: " + Ca + " != " + Rb);
        }


    }
}

C语言版,顺利通过,原理相同:

#include 

int main()
{
    int A[200][200], B[200][200];
    int Ra, Ca, Rb, Cb;
    scanf("%d %d", &Ra, &Ca);

    for (int i = 0; i < Ra; i++) {
        for (int j = 0; j < Ca; j++) {
            scanf("%d", &A[i][j]);
        }
    }

    scanf("%d %d", &Rb, &Cb);

    for (int i = 0; i < Rb; i++) {
        for (int j = 0; j < Cb; j++) {
            scanf("%d", &B[i][j]);
        }
    }

    if (Ca == Rb) 
    {
        printf("%d %d\n", Ra, Cb);
        //int C[200][200];

        for (int i = 0; i < Ra; i++) 
        {
            for (int j = 0; j < Cb; j++) 
            {
                int sum = 0; 
                for (int k = 0; k < Ca; k++) 
                {
                    sum += A[i][k] * B[k][j];
                }
                printf("%d", sum);

                if (j != Cb-1) 
                {
                    printf(" ");
                }
            }
            printf("\n");
        }
    }
    else {
        printf("Error: %d != %d\n", Ca, Rb);
    }

    return 0;
}

你可能感兴趣的:(PAT,JAVA,C)