矩阵乘法

 

 

 

 

矩阵乘法的运算量与矩阵乘法的顺序强相关。


例如:

    A是一个50×10的矩阵,B是10×20的矩阵,C是20×5的矩阵

 

计算A*B*C有两种顺序:((AB)C)或者(A(BC)),前者需要计算15000次乘法,后者只需要3500次。

 

编写程序计算不同的计算顺序需要进行的乘法次数

 

public static int getNo(String str,int[][] data) {
        int total=0;
        //读右括号
        for(int i=0;i<str.length();i++) {
            char c=str.charAt(i);
            if(c==')') {
                for(int j=i-1;j>=0;j--) {
                    char c1=str.charAt(j);
                    if(c1=='(') {
                        while(str.charAt(j+2)!=')') {
                            char c2=str.charAt(j+1);
                            char c3=str.charAt(j+2);
                            total+=data[c2-65][0]*data[c2-65][1]*data[c3-65][1];
                            //需要改变数组,改变字符串
                            data[c2-65][1]=data[c3-65][1];
                            str=str.substring(0,j+2)+str.substring(j+3);
                        }
                        //i位置的)与j为止的(要删除
                        //str已经变短,j+1不见了,i--
                        i--;
                        str=(j==0?"":str.substring(0,j))+str.substring(j+1,i)+(i==str.length()-1?"":str.substring(i+1));
                        //i指向原来左括号的位置
                        i=j;
                        break;
                    }
                }
            }
        }
        return total;
    }public static int getNo(String str,int[][] data) {
        int total=0;
        //读右括号
        for(int i=0;i<str.length();i++) {
            char c=str.charAt(i);
            if(c==')') {
                for(int j=i-1;j>=0;j--) {
                    char c1=str.charAt(j);
                    if(c1=='(') {
                        while(str.charAt(j+2)!=')') {
                            char c2=str.charAt(j+1);
                            char c3=str.charAt(j+2);
                            total+=data[c2-65][0]*data[c2-65][1]*data[c3-65][1];
                            //需要改变数组,改变字符串
                            data[c2-65][1]=data[c3-65][1];
                            str=str.substring(0,j+2)+str.substring(j+3);
                        }
                        //i位置的)与j为止的(要删除
                        //str已经变短,j+1不见了,i--
                        i--;
                        str=(j==0?"":str.substring(0,j))+str.substring(j+1,i)+(i==str.length()-1?"":str.substring(i+1));
                        //i指向原来左括号的位置
                        i=j;
                        break;
                    }
                }
            }
        }
        return total;
    }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

执于代码

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值