MATRIX MULTIPLICATION CALCULATOR - ICPC 2018 Malaysia

时间限制: 1 Sec 内存限制: 128 MB

题目描述

Matrix multiplication is a basic tool of linear algebra, and has numerous applications in many areas of mathematics, as well as in applied mathematics, computer graphics, physics, and engineering.
We can only multiply two matrices if their dimensions are compatible, which means the number of columns in the first matrix is the same as the number of rows in the second matrix.
If A = [aij ] is an m×n matrix and B = [bij ] is an n×q matrix, the product AB is an m×q matrix.
The product AB is defined to be the m×q matrix C = [cij ] such that 在这里插入图片描述

Your task is to design a matrix multiplication calculator to multiply two matrices and display the output. If the matrices cannot be multiplied, display “undefined”

输入

The input consists of a few test cases. For each test case, the first line of input is 4 positive integers, M, N, P and Q (1 ≤ M, N, P, Q ≤ 20). M and N represent the dimension of matrix A, while P and Q represent the dimension of matrix B. The following M lines consist of the data for
matrix A followed by P lines that contains the data for matrix B as shown in the sample input.
The test data ends when M, N, P and Q are 0.

输出

For each test case, the output contains a line in the format “Case #x:”, where x is the case number (starting from 1). The following line(s) is the output of the matrix multiplication.

样例输入

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

样例输出

Case #1:
| 40 46 |
| 32 38 |
Case #2:
undefined

#include<bits/stdc++.h>
using namespace std;
int m,n,p,q;
int a[25][25],b[25][25];
int main()
{
    int t=1;
    while(1){
    	cin>>m>>n>>p>>q;
	    if(m==0||n==0||p==0||q==0) return 0;
        for(int i=0;i<m;i++){
    	    for(int j=0;j<n;j++){
    		    cin>>a[i][j];
		    }
	    } 
	    for(int i=0;i<p;i++){
		    for(int j=0;j<q;j++){
			    cin>>b[i][j];
		    }
	    }
	    printf("Case #%d:\n",t);
	    if(n==p){
		    for(int i=0;i<m;i++){
			    printf("| ");
		    	for(int j=0;j<q;j++){
				    int c=0;
		    		for(int k=0;k<n;k++)
		    		    c+=a[i][k]*b[k][j];
				    printf("%d ",c);
				}
				printf("|\n");
			}
	    }else printf("undefined\n");
	    t++;
	}
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值