ZOJ1094 Matrix Chain Multiplication

来源:互联网 发布:数据挖掘技术研究 编辑:程序博客网 时间:2024/06/11 18:43

栈的入门题,比较经典。


题意:给出一个矩阵乘法表达式,判断运算是否合法,若合法则输出乘法运算的次数。


思路:乘法运算次数很好解决,关键是得到正确的运算顺序。根据题意,()之间有两项相乘,因此每遇到一个字母,就压入栈;一旦来到")",表明有两项需要相乘,那么取出矩阵栈顶的两项,判断是否合法,把相乘的结果压入栈中。


代码

#include <iostream>#include <stack>using namespace std;struct node{    char c;    int m, n;};int main(){    int t;    while(cin >> t){        node p[30];        for(int i = 0; i < t; i++){            char c;            int m, n;            cin >> c >> m >> n;            p[i].c = c;            p[i].m = m;            p[i].n = n;        }        string s;        while(cin >> s && !cin.eof()){            int cnt = 0, flag = 1;            stack<node> u;            for(int i = 0; s[i] != '\0'; i++){                if(s[i] >= 'A' && s[i] <= 'Z'){                    node x;                    for(int j = 0; j < t; j++){                        if(p[j].c == s[i]){                            x.c = s[i];                            x.m = p[j].m;                            x.n = p[j].n;                            break;                        }                    }                    u.push(x);                }                else if(s[i] == ')'){                    node x = u.top();                    u.pop();                    node y = u.top();                    u.pop();                    if(x.m != y.n){                        cout << "error" << endl;                        flag = 0;                        break;                    }                    cnt += x.n * x.m * y.m;                    x.m = y.m;                    u.push(x);                }            }            if(flag) cout << cnt << endl;        }    }    return 0;}


0 0
原创粉丝点击