華為OJ——矩陣乘法計算量估算
阿新 • • 發佈:2019-02-20
矩陣乘法計算量估算
題目描述
矩陣乘法的運算量與矩陣乘法的順序強相關。例如:
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; }