HDU 1082 Matrix Chain Multiplication

评估多个矩阵乘法的基本运算次数

乍一看与分治算法有关,其实题目是个模拟矩阵相乘次数的问题,自定义类型存储矩阵,主要操作用栈实现。遇到'('继续,遇到')'算栈顶两个矩阵相乘并再放进栈顶,附代码

 

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstring>
 4 #include <stack>
 5 using namespace std;
 6 struct Max {
 7     int row;
 8     int col;
 9 } m[100];
10 bool flg;
11 int n,num;
12 char c,ch[100];
13 int main() {
14     //freopen("C:\\CODE\\in.txt", "r", stdin);
15     //freopen("C:\\CODE\\out.txt","w",stdout);
16     scanf("%d",&n);
17     for(int i=0; i<n; i++) {
18         cin>>c>>m[i].row>>m[i].col;
19     }
20     getchar();
21     while(gets(ch)) {
22         stack<int> s;
23         flg=false;
24         int x=30;
25         num=0;
26         for(int i=0; i<strlen(ch); i++) {
27             if(ch[i]=='(')
28                 continue;
29             if(ch[i]==')') {
30                 int a=s.top();
31                 s.pop();
32                 int b=s.top();
33                 s.pop();
34                 if(m[a].row!=m[b].col) {
35                     flg=true;
36                     break;
37                 } else {
38                     num+=(m[a].row*m[a].col*m[b].row);
39                     m[x].row=m[b].row;
40                     m[x].col=m[a].col;
41 
42                     s.push(x);
43                     x++;
44                 }
45             } else {
46                 s.push(ch[i]-'A');
47             }
48         }
49         if(flg)
50             puts("error");
51         else
52             printf("%d\n",num);
53     }
54 
55     //fclose(stdin);
56     return 0;
57 }

 

posted @ 2016-02-02 14:41  闪耀子  阅读(156)  评论(0编辑  收藏  举报