442 - Matrix Chain Multiplication

欢迎folk或者star我的repo:https://github.com/guopeiming/algorithm-training,每天更新一道oj入门紫皮书上的题目或者oj、LeetCode,持续更新中

主要就是模拟矩阵的计算过程,注意每一次栈都要清空,否则,上一次残留的东西会影响后一次的计算。
整个的计算过程就类似前、后、中缀表达式的计算过程,很类似计算器,比较简单的水题
#include <stdio.h>
#include <stack>
#include <string.h>
using namespace std;

void mul();

int mat[60], n;
stack<int> s;
char str[200];

int main(){
    scanf("%d", &n);
    for(int i = 0; i < n; ++i){
        getchar();
        char name;
        scanf("%c", &name);
        scanf("%d %d", mat+2*(name-'A'), mat+2*(name-'A')+1);
    }
    while(~scanf("%s", str)){
        mul();
        while(!s.empty()){
            s.pop();
        }
    }
    return 0;
}
void mul(){
    int res = 0;
    for(int i = 0; i < strlen(str); ++i){
        if(str[i] == '('){
            continue;
        }else if(str[i] == ')'){
            int matSize[4];
            for(int j = 3; j >= 0; --j){
                matSize[j] = s.top();
                s.pop();
            }
            if(matSize[1] != matSize[2]){
                printf("error\n");
                return;
            }else{
                res += matSize[0]*matSize[1]*matSize[3];
                s.push(matSize[0]);
                s.push(matSize[3]);
            }
        }else{
            s.push(mat[(str[i]-'A')*2]);
            s.push(mat[(str[i]-'A')*2+1]);
        }
    }
    printf("%d\n", res);
}
// Sample Input
// 9
// A 50 10
// B 10 20
// C 20 5
// D 30 35
// E 35 15
// F 15 5
// G 5 10
// H 10 20
// I 20 25
// A
// B
// C
// (AA)
// (AB)
// (AC)
// (A(BC))
// ((AB)C)
// (((((DE)F)G)H)I)
// (D(E(F(G(HI)))))
// ((D(EF))((GH)I))

// Sample Output
// 0
// 0
// 0
// error
// 10000
// error
// 3500
// 15000
// 40500
// 47500
// 15125

//数据结构栈的使用
//牢记每次计算之前栈一定要先清空

猜你喜欢

转载自www.cnblogs.com/guopinghai/p/11565864.html
今日推荐