Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Matrix Chain Multiplication, Parenthesization Evaluation
- // Given the dimensions of "N" number of matrices and the Parenthesization (Multiplication Procedure), have to find the number of multiplications operations required for these "N" matrices using the given procedure.
- /* Sample Input: 10 20 30 40 50
- ( 1 ( 2 3 ) 4 ) [Spaces are mandatory]
- */
- #include <iostream>
- #include <string>
- #include <sstream>
- #define SIZE 100
- using namespace std;
- struct matrix {
- int row;
- int col;
- };
- class stack {
- private:
- struct matrix M;
- class stack *next;
- public:
- stack(): next(NULL) {}
- ~stack() {}
- class stack *push (struct matrix m) {
- class stack *temp = new stack;
- temp -> M = m;
- temp -> next = this;
- return temp;
- }
- class stack *pop() {
- if (this != NULL) {
- class stack *temp = this -> next;
- delete this;
- return temp;
- }
- else
- return this;
- }
- struct matrix top() {
- if (this != NULL)
- return this -> M;
- else {
- struct matrix X;
- X.row = 0;
- X.col = 0;
- return X;
- }
- }
- };
- int main() {
- string line;
- cout << "Enter the P Values: ";
- getline(cin, line);
- istringstream Pv(line);
- int N = -1;
- int P[SIZE];
- while (Pv >> line)
- stringstream(line) >> P[++N];
- struct matrix M[SIZE];
- for (int i = 0; i < N; i++) {
- M[i].row = P[i];
- M[i].col = P[i + 1];
- }
- cout << "Enter the Expression: ";
- getline(cin, line);
- istringstream Exp(line);
- struct matrix a, b, c;
- class stack *S = NULL;
- int x, sum = 0;
- while (Exp >> line) {
- if (line == ")") {
- a = S -> top();
- S = S -> pop();
- b = S -> top();
- S = S -> pop();
- sum += b.row * a.row * a.col;
- c.row = b.row;
- c.col = a.col;
- S = S -> push(c);
- }
- else if (line != "(") {
- stringstream(line) >> x;
- S = S -> push (M[x - 1]);
- }
- }
- cout << "Number of Multiplication Required: " << sum << endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement