矩阵链乘(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 }

转载于:https://www.cnblogs.com/pgzhang/p/9385732.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值