华为OJ——矩阵乘法计算量估算
来源:互联网 发布:淘宝日本代购店推荐 编辑:程序博客网 时间:2024/05/22 00:54
矩阵乘法计算量估算
题目描述
矩阵乘法的运算量与矩阵乘法的顺序强相关。
例如:
A是一个50×10的矩阵,B是10×20的矩阵,C是20×5的矩阵
计算A*B*C有两种顺序:((AB)C)或者(A(BC)),前者需要计算15000次乘法,后者只需要3500次。
编写程序计算不同的计算顺序需要进行的乘法次数
输入描述:
输入多行,先输入要计算乘法的矩阵个数n,每个矩阵的行数,列数,总共2n的数,最后输入要计算的法则
输出描述:
输出需要进行的乘法次数
输入例子:
3
50 10
10 20
20 5
(A(BC))
输出例子:
3500
解答代码:
#include <iostream>#include <vector>#include <stack>#include <string>#include <cstring>using namespace std;typedef struct node{ int row; int col;} NODE;int main(){ int i,n; string oper; stack<char> sta; freopen("1.txt","r",stdin); while( cin >> n) { int result=0; NODE array[100]; char oper[100]; //输入矩阵的行和列 for(i=0; i<n; i++) cin>>array[i].row>>array[i].col; //操作序列 cin>>oper; int length=strlen(oper); //栈清空 while(sta.empty()==false) sta.pop(); for(i=0; i<length; i++) { char ch=oper[i]; if(ch=='(') sta.push(ch); if(ch>='A' && ch<= 'Z') { if(!sta.empty()) { if(sta.top()>='A' && sta.top()<='Z') { int index1=sta.top()-'A'; sta.pop(); int index2=ch-'A'; result+=array[index1].row * array[index1].col * array[index2].col; //将新的结点放入栈中(矩阵经过乘运算后得到新矩阵的行和列) array[n].row=array[index1].row; array[n].col=array[index2].col; char temp=n+'A'; sta.push(temp); n++; } else { sta.push(ch); } } else sta.push(ch); } if(ch==')') { if(sta.top()>='A' && sta.top()<='Z') { int index3=sta.top()-'A'; sta.pop(); int index4; if(!sta.empty()) { if(sta.top()>='A' && sta.top()<='Z') { index4=sta.top()-'A'; sta.pop(); result+=array[index4].row *array[index4].col * array[index3].col; //将新的矩阵行和列存入数组 array[n].row=array[index4].row; array[n].col=array[index3].col; if(sta.top()=='(') { sta.pop(); } char charA=n+'A'; sta.push(charA); n++; } else { sta.pop(); sta.push(index3+'A'); } } } } } //取出栈中的数 char staOut[100]; int len=0; while(!sta.empty()) { char tempCh=sta.top(); if(tempCh=='(' || tempCh==')') sta.pop(); else { staOut[len++]=tempCh; sta.pop(); } } //计算乘法运算量 for(i=len-1; i>=1; i--) { int index5=staOut[i]-'A'; int index6=staOut[i-1]-'A'; result+=array[index5].row * array[index5].col * array[index6].col; array[n].row=array[index5].row; array[n].col=array[index6].col; staOut[i-1]=n+'A'; n++; } cout<<result<<endl; } return 0;}
2 0
- 华为OJ——矩阵乘法计算量估算
- 华为OJ——矩阵乘法计算量估算
- 华为OJ矩阵乘法计算量估算
- 【华为OJ】【098-矩阵乘法计算量估算】
- 矩阵乘法计算量估算
- 华为OJ(矩阵乘法计算量估计)
- 华为机试:无线OSS-高精度整数加法、矩阵乘法计算量估算
- 华为OJ——矩阵乘法
- 华为OJ——矩阵乘法
- 华为OJ——矩阵乘法
- 【华为oj】矩阵乘法
- 华为oj 矩阵乘法
- 华为oj 矩阵乘法
- 【华为OJ】矩阵乘法
- 华为OJ:矩阵乘法
- 华为OJ(矩阵乘法)
- 【华为OJ】【042-矩阵乘法】
- 华为OJ 初级:矩阵乘法
- 关于二叉树的常见题型
- web 问题
- 《leetCode》:Different Ways to Add Parentheses
- 假设某棵二叉查找树的所有键均为1到10的整数,现在我们要查找5。下面____不可能是键的检查序列。
- 安卓项目之淘忆1.0版本的简述
- 华为OJ——矩阵乘法计算量估算
- 89. Gray Code
- 【ASP.NET】asp.net中的对象
- iOS-浅谈block
- 华为OJ——百钱买百鸡问题
- 求a,b两数的最大公约数的两种方法
- Codeforces 580B Kefa and Company
- win10分盘
- java Fork/Join多线程发送短信