矩阵链乘(UVa 442)

  结构体 struct matrix 用来保存矩阵的行和列;

  map<string,matrix> 用来保存矩阵名和相应的行列数;

  stack<string> 用来保存表达式中遇到的矩阵名,并将每次乘法运算后的矩阵压入栈中;

C++11 代码如下:

 1 #include<iostream>
 2 #include<map>
 3 #include<string>
 4 #include<stack>
 5 using namespace std;
 6 
 7 struct matrix {
 8     int row;
 9     int column;
10 };
11 
12 int main() {
13     int n; string ch;
14     string str;
15     int li, co;
16     map<string, matrix>m;
17     cin >> n;
18     for (int i = 0; i < n; i++) {
19         cin >> ch >> li >> co;
20         m[ch].row = li;
21         m[ch].column = co;
22     }
23     while ((cin >> str)){    
24         stack<string>s;
25         string a, b;
26         int sum = 0;
27         bool flag = true;
28         for (int i = 0; i < str.length(); i++) {
29             if (str[i] == '(') continue;
30             else if (str[i] == ')') {
31                 a = s.top(); s.pop();
32                 b = s.top(); s.pop();
33                 if (m[b].column == m[a].row) {
34                     sum += m[b].row*m[b].column*m[a].column;
35                     string ba;
36                     ba = b + a;
37                     s.push(ba);
38                     m[ba].row = m[b].row;
39                     m[ba].column = m[a].column;
40                 }
41                 else {
42                     flag = false;
43                     break;
44                 }
45             }
46             else {
47                 string s2;
48                 s2 = str[i];
49                 s.push(s2);
50             }
51         }
52         if(flag) cout << sum << endl;
53         else cout << "error" << endl;
54     }
55     return 0;
56 }
posted on 2018-07-29 16:25  Pink.Pig  阅读(442)  评论(0编辑  收藏  举报