您的位置:首页 > 大数据 > 人工智能

UVa 442 - Matrix Chain Multiplication

2013-07-29 11:43 393 查看
/*
栈操作
*/
#include <cstdio>
#include <cstring>
#include <cctype>
#include <algorithm>
using namespace std;
const int MAXN = 26;
const int BUFF_SIZE = 1024;
int r[MAXN], c[MAXN];
int n;
char buff[BUFF_SIZE];
int str[BUFF_SIZE], stc[BUFF_SIZE], fr;

void push(int a, int b)
{
str[fr] = a;
stc[fr++] = b;
}

void pop(int &a, int &b)
{
fr--;
a = str[fr];
b = stc[fr];
}

int main() {
#ifndef ONLINE_JUDGE
freopen("in.txt", "r", stdin);
#endif
scanf("%d\n", &n);
int j;
for(int i=0; i<n; i++) {
j = getchar() - 'A';
scanf("%d%d\n", &r[j], &c[j]);
}
while(gets(buff)) {
if(buff[0] != '(') {
printf("0\n"); continue;
}
int sum = 0;
char *p = buff;
fr = 0;
while(*p) {
if(*p == ')') {
int r1, c1, r2, c2;
pop(r1, c1);
pop(r2, c2);
if(c2 != r1) {
sum = -1;  break;
}
sum += r2 * c2 * c1;
push(r2, c1);
} else if(*p != '('){
int i = *p - 'A';
push(r[i], c[i]);
}
p++;
}
if(sum < 0) printf("error\n");
else printf("%d\n", sum);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: