ACM篇:Uva 442 -- Matrix Chain Multiplication

来源:互联网 发布:怎么删除手机淘宝评论 编辑:程序博客网 时间:2024/05/05 07:12

stack

#include <iostream>#include <cstdio>#include <cstring>#include <vector>#include <stack>using namespace std;const int N = 26;int n;int readchar(){    int ch;    while ((ch=getchar()) != EOF)        if (isalpha(ch))            return ch;}struct Node{    int r;    int c;    Node (int r=0, int c=0)    {        this->r = r;        this->c = c;    }};Node matrix[N];void read_matrix(){    scanf("%d", &n);    for (int i = 0; i < n; i++)    {        int id = readchar() - 'A';        scanf("%d%d", &matrix[id].r, &matrix[id].c);    }}long long _calculate(char *s){    Node x, y;    stack<Node> e;    long long ret = 0;    for (char *p = s; *p; p++)    {        if (isalpha(*p))            e.push(Node(matrix[*p-'A'].r, matrix[*p-'A'].c));        else if (*p == ')')        {            y = e.top();            e.pop();            x = e.top();            e.pop();            if (x.c != y.r)                return -1;            ret += x.r * x.c * y.c;            e.push(Node(x.r, y.c));        }    }    return ret;}int main(){    long long ans;    char exp[N * 100];    read_matrix();    while (scanf("%s", exp) == 1)        ((ans = _calculate(exp)) == -1) ? (printf("error\n")) : (printf("%lld\n", ans));    return 0;}
0 0