hdu-1082 Matrix Chain Multiplication---栈的运用

题目链接:

http://acm.hdu.edu.cn/showproblem.php?pid=1082

题目大意:

题意大致是N个矩阵,如果要求计算的矩阵例如(AB),如果A的列等于B的行,进行:A.行*A.列*B.列这样的运算,如果A的列不等于B的行,输出error。

思路:

大致感觉和逆波兰表达式类似,用stack来进行存取会比较方便。如果计算(A(BC)),那么得先计算BC,再与A乘。可以以')'为标志,出现)则弹栈,取出C、B(注意栈顺序,第一次取出的是后面的元素,第二次取出的才是前面的元素)。计算之后再将新的行列入栈,遇到下一个)时与A计算。

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 #include<algorithm>
 5 #include<cmath>
 6 #include<queue>
 7 #include<stack>
 8 #include<map>
 9 using namespace std;
10 typedef long long ll;
11 const int maxn = 1e6 + 10;
12 const int INF = 1 << 30;
13 int T, n, m;
14 struct node
15 {
16     ll x, y;
17     node(){}
18     node(ll x, ll y):x(x), y(y){}
19 };
20 node a[50];
21 map<char, int>Map;
22 int main()
23 {
24     cin >> n;
25     string s;
26     ll x, y;
27     for(int i = 0; i < n; i++)
28     {
29         cin >> s >> x >> y;
30         Map[s[0]] = i;
31         a[i].x = x;
32         a[i].y = y;
33     }
34     while(cin >> s)
35     {
36         stack<node>q;
37         ll ans = 0;
38         bool ok = 1;
39         for(int i = 0; i < s.size(); i++)
40         {
41             if(s[i] == '(')
42             {
43                 continue;
44             }
45             else if(s[i] == ')')
46             {
47                 if(q.empty()){ok = 0; break;}
48                 node b = q.top();//注意,第一次取出来的是b,第二次才是a
49                 q.pop();
50                 if(q.empty()){ok = 0; break;}
51                 node a = q.top();
52                 q.pop();
53                 //cout<<a.x<<" "<<a.y<<" "<<b.x<<" "<<b.y<<endl;
54                 if(a.y != b.x){ok = 0; break;}
55                 q.push(node(a.x, b.y));
56                 ans += a.x * a.y * b.y;
57             }
58             else
59             {
60                 q.push(a[Map[s[i]]]);
61             }
62         }
63         if(!ok)cout<<"error"<<endl;
64         else cout<<ans<<endl;
65     }
66     return 0;
67 }
原文地址:https://www.cnblogs.com/fzl194/p/8698883.html