uva442Matrix Chain Multiplication(栈)
题目链接:
lrj--p141。
1 #include<iostream> 2 #include<cstdio> 3 #include<cstring> 4 #include<string> 5 #include<stack> 6 #include<cctype> 7 using namespace std; 8 9 struct matrix 10 { 11 int a,b; 12 matrix (int x=0,int y=0):a(x),b(y) {} 13 }m[26]; 14 int main() 15 { 16 int n; 17 char ch; 18 string ss; 19 while(scanf("%d",&n)!=EOF&&n) 20 { 21 for(int i=0;i<n;i++) 22 { 23 cin>>ch; 24 scanf("%d%d",&m[ch-'A'].a,&m[ch-'A'].b); 25 } 26 while( cin>>ss ) 27 { 28 int ans=0; 29 int ok=0; 30 stack<matrix> s; 31 while(!s.empty()) s.pop(); 32 int len=ss.length(); 33 for(int i=0;i<len;i++) 34 { 35 if(isalpha(ss[i])) s.push(m[ss[i]-'A']); 36 else if(ss[i]==')') 37 { 38 matrix m2=s.top(); 39 s.pop(); 40 matrix m1=s.top(); 41 s.pop(); 42 if(m1.b!=m2.a) {ok=1;break;} 43 ans+=m1.a*m1.b*m2.b; 44 s.push(matrix(m1.a,m2.b)); 45 } 46 47 } 48 if(!ok) printf("%d\n",ans); 49 else puts("error"); 50 } 51 } 52 }