442 - Matrix Chain Multiplication

Welcome to folk or star my repo: https://github.com/guopeiming/algorithm-training , updated daily or a topic oj oj the introductory Purple Book, LeetCode, continuous update

Mainly analog matrix calculation process, pay attention to every stack must be empty, otherwise, the last remaining things will affect one of the calculations.
The whole process is similar to the previous calculation, the calculation process infix expressions, very similar to a calculator, a relatively simple water problem
#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)){
        I have();
        while(!s.empty()){
            s.pop();
        }
    }
    return 0;
}
void mul(){
    int a = 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

// Use the stack data structure
// bear in mind that each stack must first emptied before computing

Guess you like

Origin www.cnblogs.com/guopinghai/p/11565864.html