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

时间:2024-09-04 12:34:38

题目链接:

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计算。

 #include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<queue>
#include<stack>
#include<map>
using namespace std;
typedef long long ll;
const int maxn = 1e6 + ;
const int INF = << ;
int T, n, m;
struct node
{
ll x, y;
node(){}
node(ll x, ll y):x(x), y(y){}
};
node a[];
map<char, int>Map;
int main()
{
cin >> n;
string s;
ll x, y;
for(int i = ; i < n; i++)
{
cin >> s >> x >> y;
Map[s[]] = i;
a[i].x = x;
a[i].y = y;
}
while(cin >> s)
{
stack<node>q;
ll ans = ;
bool ok = ;
for(int i = ; i < s.size(); i++)
{
if(s[i] == '(')
{
continue;
}
else if(s[i] == ')')
{
if(q.empty()){ok = ; break;}
node b = q.top();//注意,第一次取出来的是b,第二次才是a
q.pop();
if(q.empty()){ok = ; break;}
node a = q.top();
q.pop();
//cout<<a.x<<" "<<a.y<<" "<<b.x<<" "<<b.y<<endl;
if(a.y != b.x){ok = ; break;}
q.push(node(a.x, b.y));
ans += a.x * a.y * b.y;
}
else
{
q.push(a[Map[s[i]]]);
}
}
if(!ok)cout<<"error"<<endl;
else cout<<ans<<endl;
}
return ;
}