标签:
题目大意:给出n个矩阵和表达式,问该表达式是否正确,如果计算正确,输出计算了多少次
解题思路:双端队列,遇到右括号时弹出后面的两个矩阵进行乘法,相乘时要注意顺序,是第二个出队列的乘上第一个出队列的。
#include<cstdio>
#include<algorithm>
#include<deque>
#include<map>
#include<cstring>
using namespace std;
#define maxn 50010
struct Matrix{
int x, y;
Matrix() {}
Matrix(int xx, int yy) {
x = xx;
y = yy;
}
}M[30];
int n;
char str[maxn];
map<char, Matrix> Map;
void solve() {
deque<Matrix> dq;
int len = strlen(str);
bool flag = true;
long long ans = 0;
for(int i = 0; i < len; i++) {
if(str[i] == ‘ ‘ || str[i] == ‘(‘)
continue;
else if(str[i] == ‘)‘) {
Matrix t2 = dq.back();
dq.pop_back();
Matrix t1 = dq.back();
dq.pop_back();
if(t1.y != t2.x) {
flag = false;
break;
}
ans += t1.x * t1.y * t2.y;
dq.push_back(Matrix(t1.x, t2.y));
}
else {
dq.push_back(Map[str[i]]);
}
}
while(!dq.empty()) {
Matrix t1 = dq.front();
dq.pop_front();
if(dq.empty())
break;
Matrix t2 = dq.front();
dq.pop_front();
if(t1.y != t2.x) {
flag = false;
break;
}
ans += t1.x * t1.y * t2.y;
dq.push_front(Matrix(t1.x, t2.y));
}
if(!flag)
printf("error\n");
else
printf("%lld\n", ans);
}
int main() {
int n, x, y;
char t, in[100];
gets(in);
sscanf(in,"%d",&n);
for(int i = 0; i < n; i++) {
gets(in);
sscanf(in,"%c%d%d", &t, &x, &y);
Map[t] = Matrix(x,y);
}
while(gets(str)) {
solve();
}
return 0;
}
UVA - 442 Matrix Chain Multiplication 双端队列
标签:
原文地址:http://blog.csdn.net/l123012013048/article/details/45607137