蓝桥杯算法训练--矩阵乘法

矩阵乘法

问题描述

  输入两个矩阵,分别是m*s,s*n大小。输出两个矩阵相乘的结果。

输入格式

  第一行,空格隔开的三个正整数m,s,n(均不超过200)。
  接下来m行,每行s个空格隔开的整数,表示矩阵A(i,j)。
  接下来s行,每行n个空格隔开的整数,表示矩阵B(i,j)。

输出格式

  m行,每行n个空格隔开的整数,输出相乘後的矩阵C(i,j)的值。

样例输入

2 3 2
1 0 -1
1 1 -3
0 3
1 2
3 1

样例输出

-3 2
-8 2

提示
矩阵C应该是m行n列,其中C(i,j)等于矩阵A第i行行向量与矩阵B第j列列向量的内积。
例如样例中C(1,1)=(1,0,-1)*(0,1,3) = 1 * 0 +0*1+(-1)*3=-3

解题思路:纯暴力即可,但是java只能拿85分,c/c++能拿100分。

import java.util.Scanner;
public class Main {
	private int m = 0,s = 0,n = 0;
	private int [][]a;
	private int [][]b;
	private int [][]c;
	public Main() {
		a = new int[200][200];
		b = new int[200][200];
		c = new int[200][200];
	}
	
	public static void main(String[] args) {
		Main main = new Main();
		
		main.get();
	}
	private void init() {
		Scanner  in = new Scanner(System.in);
		m = in.nextInt();
		s = in.nextInt();
		n= in.nextInt();
		
		for(int i = 0 ;i<m;i++) {
			for(int j = 0 ; j<s;j++) {
				a[i][j] = in.nextInt();
			}
		}
		for(int i = 0 ;i<s;i++) {
			for(int j = 0 ; j<n;j++) {
				b[i][j] = in.nextInt();
			}
		}
		in.close();
	}
	/**
	 * a[1][1] * b[1][1] +a[1][2]*b[2][1] + a[1][3]*b[3][1] .....
	 * a[1][1] * b[1][2] +a[1][2]*b[2][2]......
	 */
	private void get() {
		init();
		for(int i = 0;i<m;i++) {
			for(int j = 0 ;j<n;j++) {
				int mult = 0;
				for(int k = 0 ; k<s;k++) {
					mult += a[i][k]*b[k][j];
				}
				c[i][j] = mult;
			}
		}
		for(int i = 0;i<m;i++) {
			for(int j = 0 ;j<n;j++) {
				System.out.print(c[i][j]);
				if(j!=n-1) {
					System.out.print(" ");
				}else if(i!=m-1) {
					System.out.println();
				}
			}
		}
	}
}

猜你喜欢

转载自blog.csdn.net/hnust_yangjieyu/article/details/83964799