矩阵乘法计算量估算
题目描述
矩阵乘法的运算量与矩阵乘法的顺序强相关。
例如:
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;
}