0
0
0
1. 云栖社区>
2. 博客>
3. 正文

## 矩阵乘法的运算量计算（华为OJ）

lovedan 2017-08-13 14:54:00 浏览664

https://www.nowcoder.com/practice/15e41630514445719a942e004edc0a5b?tpId=37&&tqId=21293&rp=1&ru=/activity/oj&qru=/ta/huawei/question-ranking

## 题目内容

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

3
50 10
10 20
20 5
(A(BC))

3500

4
50 10
10 20
20 5
5 6
(A(BCD))

9000

## 放码过来

``````
#include <iostream>
#include <string>
#include <cmath>
#include <algorithm>
#include <cstring>
#include <vector>
#include <climits>
#include <stack>

using namespace std;

void EX21_clean() {
int n;

struct Dim { int r, c; };

while (cin >> n) {
vector<Dim> vd;
Dim dim;

for (int i = 0; i < n; i++) {
cin >> dim.r >> dim.c;
vd.push_back(dim);
}

string s; cin >> s;
stack<Dim> stk;
int ans = 0;
stack<char> cal;
int delta;

int idx;
char ch1, ch2;

for (int i = 0; i < s.length(); i++) {
if (s[i] == ')') {
if (cal.size() != 1) {
ch1 = cal.top(); cal.pop();
if (ch1 == '(') {
continue;
}
idx = ch1 - 'A';
dim = vd[idx];

delta = dim.c;
while (!cal.empty()) {
ch2 = cal.top(); cal.pop();
idx = ch2 - 'A';
if (ch2 == '(') {
cal.push(ch1); //注意此处
break;
}
dim = vd[idx];
delta *= dim.c;
}
delta *= dim.r;
ans += delta;
}
}
else {
cal.push(s[i]);
}
}
cout << ans << endl;
}
}

int main() {
//EX1();
//EX2();
//EX3();
//EX4();
//EX5();
//EX6();
//EX7();

//EX11();
//EX12();
//EX13();
//EX14();
//EX15();
//EX16();
//EX17();

EX21_clean();

return 0;
}``````

lovedan
+ 关注

corcosa 13587人浏览