UV 442 Matrix Chain Multiplication——思路题

来源:互联网 发布:pdf.js如何使用 编辑:程序博客网 时间:2024/05/01 01:56
#include <iostream>#include <cstdio>#include <cstring>#include <stack>#include <cctype>using namespace std;struct matrix{    int a, b;    matrix(int x = 0, int y = 0){//构造函数初始化a、b        a = x, b = y;    }}m[26];int main(){    stack<matrix> s;    int n; scanf("%d", &n);    for (int i = 0; i < n; i++) {        char ch;        getchar();//每次都接收一个换行        ch = getchar();        int temp = ch - 'A';        scanf("%d %d", &m[temp].a, &m[temp].b);    }    string expr;    while (cin >> expr) {        int len = expr.length();        bool error = false;        int ans = 0;        for (int i = 0; i < len; i++) {            if (isalpha(expr[i])) s.push(m[expr[i] - 'A']);            else if (expr[i] == ')') {                matrix m2 = s.top(); s.pop();                matrix m1 = s.top(); s.pop();                if (m1.b != m2.a) {error = true; break;}                ans += m1.a*m1.b*m2.b;                s.push(matrix(m1.a, m2.b));            }        }        if (error) printf("error\n");        else printf("%d\n", ans);    }    return 0;}

1 0