hdu 1082 Matrix Chain Multiplication

  我使用了stack来模拟进行矩阵乘法的过程,当遇到'('时跳过当遇到')'时从栈顶弹出两个矩阵,计算需要相乘的次数,把计算结果入栈,并加到ans中,遇到矩阵时入栈。表达式处理完之后如何stack的元素多余一个,则弹出两个矩阵,计算矩阵结果,再把结果入栈,并把需要的相乘次数累加到ans中,反复执行这个过程直到stack中只有一个元素。

/* Author: ACb0y Date: 2010-7-10 Result: AC Description: hdu 1082 Matrix Chain Multiplication */ #include <iostream> #include <map> using namespace std; struct node { char name; int n; int m; }; node data[30]; node stack[100]; int top; int main() { int c; int ans; char str[100]; node a, b, r; map<char, int> m; #ifndef ONLINE_JUDGE freopen("1082.txt", "r", stdin); #endif scanf("%d/n", &c); int i; for (i = 0; i < c; i++) { scanf("%c %d %d/n", &data[i].name, &data[i].n, &data[i].m); m[data[i].name] = i; } while (scanf("%s/n", str) != EOF) { int i; int len = strlen(str); ans = 0; int flag = 1; top = 0; for (i = 0; i < len; i++) { if (str[i] == '(') { continue; } else if (str[i] == ')') { a = stack[--top]; b = stack[--top]; if (b.m != a.n) { flag = 0; break; } ans += b.n * b.m * a.m; r.n = b.n; r.m = a.m; stack[top++] = r; } else { int pos = m[str[i]]; stack[top++] = data[pos]; } } if (flag) { while (top > 1) { a = stack[--top]; b = stack[--top]; if (b.m != a.n) { flag = 0; break; } ans += b.n * b.m * a.m; r.n = b.n; r.m = a.m; stack[top++] = r; } } if (flag) { cout << ans << endl; } else { cout << "error" << endl; } } return 0; }

你可能感兴趣的:(c,Matrix,2010)