NC17386. Matrix Multiplication
描述
输入描述
The first line of the input is T(1≤ T ≤ 100), which stands for the number of test cases you need to solve.
For each test case, the first line contains four 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. (-100 ≤ aij ≤ 100, -100 ≤ bij ≤ 100).
输出描述
For each test case, print the case number and the output of the matrix multiplication.
示例1
输入:
2 2 3 3 2 1 1 1 1 2 3 2 3 4 5 6 7 2 3 2 3 1 2 3 1 2 3 2 3 4 2 3 4
输出:
Case 1: 12 15 28 34 Case 2: ERROR
C++11(clang++ 3.9) 解法, 执行用时: 2ms, 内存消耗: 376K, 提交时间: 2020-09-11 16:16:47
#include<cstdio> using namespace std; int A[25][25], B[25][25]; int main(){ int n1, m1, n2, m2, i, j, k, c, T, t; scanf("%d", &T); for(t = 1;t <= T;t++){ scanf("%d%d%d%d", &n1, &m1, &n2, &m2); for(i = 1;i <= n1;i++)for(j = 1;j <= m1;j++)scanf("%d", &A[i][j]); for(i = 1;i <= n2;i++)for(j = 1;j <= m2;j++)scanf("%d", &B[i][j]); printf("Case %d:\n", t); if(m1 != n2){ printf("ERROR\n"); continue; }for(i = 1;i <= n1;i++){ for(j = 1;j <= m2;j++){ for(k = 1, c = 0;k <= m1;k++)c += A[i][k] * B[k][j]; printf("%d ", c); }printf("\n"); } }return 0; }
C++14(g++5.4) 解法, 执行用时: 3ms, 内存消耗: 472K, 提交时间: 2018-08-05 12:17:05
#include<bits/stdc++.h> using namespace std; int main(){ int T;cin>>T; int kase=0; while(T--){ kase++; printf("Case %d:\n",kase); int m,n,p,q; cin>>m>>n>>p>>q; int a[22][22],b[22][22],c[22][22]={}; for (int i=1;i<=m;i++) for (int j=1;j<=n;j++)cin>>a[i][j]; for (int i=1;i<=p;i++) for (int j=1;j<=q;j++)cin>>b[i][j]; if (n!=p){cout<<"ERROR"<<endl;continue;} for (int i=1;i<=m;i++) for (int j=1;j<=q;j++) for (int k=1;k<=n;k++)c[i][j]+=a[i][k]*b[k][j]; for (int i=1;i<=m;i++){ for (int j=1;j<=q;j++)cout<<c[i][j]<<' '; cout<<endl; } } }