前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >算法提高 矩阵相乘

算法提高 矩阵相乘

作者头像
AI那点小事
发布2020-04-20 17:05:09
5220
发布2020-04-20 17:05:09
举报
文章被收录于专栏:AI那点小事AI那点小事

问题描述   小明最近在为线性代数而头疼,线性代数确实很抽象(也很无聊),可惜他的老师正在讲这矩阵乘法这一段内容。   当然,小明上课打瞌睡也没问题,但线性代数的习题可是很可怕的。   小明希望你来帮他完成这个任务。

  现在给你一个ai行aj列的矩阵和一个bi行bj列的矩阵,   要你求出他们相乘的积(当然也是矩阵)。   (输入数据保证aj=bi,不需要判断) 输入格式   输入文件共有ai+bi+2行,并且输入的所有数为整数(long long范围内)。   第1行:ai 和 aj   第2~ai+2行:矩阵a的所有元素   第ai+3行:bi 和 bj   第ai+3~ai+bi+3行:矩阵b的所有元素 输出格式   输出矩阵a和矩阵b的积(矩阵c)   (ai行bj列) 样例输入 2 2 12 23 45 56 2 2 78 89 45 56 样例输出 1971 2356 6030 7141

代码语言:javascript
复制
import java.io.BufferedInputStream;
import java.math.BigInteger;
import java.util.Scanner;

public class Main {

    public static BigInteger[][] Mul(BigInteger[][] A ,int col1,BigInteger[][] B,int col2){
        BigInteger[][] C = new BigInteger[A.length][col2];
        for ( int i = 0 ; i < A.length ; i++){
            for ( int k = 0 ; k < col2 ; k++){
                BigInteger sum = BigInteger.ZERO;
                for ( int j = 0 ; j < col1 ; j++){
                    sum = sum.add(A[i][j].multiply(B[j][k]));
                }
                C[i][k] = sum; 
            }
        }
        return C;
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner in = new Scanner(new BufferedInputStream(System.in));
        int i,j,m,n;
        i = in.nextInt();
        j = in.nextInt();
        BigInteger[][] A = new BigInteger[i][j];
        for ( int a = 0 ; a < i ; a++){
            for ( int b = 0 ; b < j ; b++){
                A[a][b] = new BigInteger(in.next());
            }
        }
        m = in.nextInt();
        n = in.nextInt();
        BigInteger[][] B = new BigInteger[m][n];
        for ( int a = 0 ; a < m ; a++){
            for ( int b = 0 ; b < n ; b++){
                B[a][b] = new BigInteger(in.next());
            }
        }
        BigInteger[][] C = Mul(A, j, B, n);
        for ( int p = 0 ; p < C.length ; p++){
            System.out.print(C[p][0]);
            for ( int q = 1 ; q < n ; q++){
                System.out.print(" "+C[p][q]);
            }
            System.out.println();
        }
        in.close();
    }

}
这里写图片描述
这里写图片描述
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档