标签:
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 1382 Accepted Submission(s): 905
1 #include<cstdio> 2 #include<cstring> 3 #include<string> 4 #include<algorithm> 5 #include<map> 6 #include<iostream> 7 using namespace std; 8 #define N 30 9 #define M 50000 10 struct Mnode{ 11 int m; 12 int n; 13 }mm[N]; 14 Mnode stk[M]; 15 16 int main() 17 { 18 int t; 19 while(~scanf("%d",&t)) 20 { 21 map<char,int> mp; 22 for(int i = 0; i < t; i++) 23 { 24 char ch; 25 int m, n; 26 getchar(); 27 scanf("%c %d %d",&ch,&m,&n); 28 mp[ch] = i; 29 mm[i].m = m; 30 mm[i].n = n; 31 } 32 char ml[1000]; 33 while(~scanf("%s",ml)) 34 { 35 int top = 0; 36 int ans = 0; 37 bool flag = 1; 38 for(int i = 0; i < strlen(ml); i++) 39 { 40 if(ml[i]<=‘Z‘&&ml[i]>=‘A‘){ 41 Mnode tm; 42 tm.m = mm[mp[ml[i]]].m; 43 tm.n = mm[mp[ml[i]]].n; 44 stk[top++] = tm; 45 } 46 else if(ml[i]==‘)‘){ 47 Mnode tm1,tm2,tm3; 48 tm2 = stk[--top]; 49 tm1 = stk[--top]; 50 if(tm1.n!=tm2.m){ puts("error"); flag = 0; break; } 51 tm3.m = tm1.m; 52 tm3.n = tm2.n; 53 ans+=tm1.m*tm1.n*tm2.n; 54 stk[top++] = tm3; 55 } 56 } 57 if(flag) printf("%d\n",ans); 58 } 59 } 60 return 0; 61 }
刘汝佳大神的代码,注意其中的构造函数的写法,表示如果没有参数的时候自动默认两个参数值都是0
1 #include<cstdio> 2 #include<stack> 3 #include<iostream> 4 #include<string> 5 using namespace std; 6 struct Matrix{ 7 int a, b; 8 Matrix(int a = 0, int b = 0):a(a),b(b){} 9 }m[26]; 10 stack<Matrix> s; 11 12 int main() 13 { 14 int n; 15 cin>>n; 16 for(int i = 0; i < n; i++){ 17 string name; 18 cin>>name; 19 int k = name[0]-‘A‘; 20 cin>>m[k].a>>m[k].b; 21 } 22 string expr; 23 while(cin>>expr){ 24 int len = expr.length(); 25 bool error = false; 26 int ans = 0; 27 for(int i = 0; i < len; i++){ 28 if(isalpha(expr[i])) s.push(m[expr[i]-‘A‘]); 29 else if(expr[i]==‘)‘){ 30 Matrix m2 = s.top();s.pop(); 31 Matrix m1 = s.top();s.pop(); 32 if(m1.b!=m2.a){error = true; break;} 33 ans += m1.a*m1.b*m2.b; 34 s.push(Matrix(m1.a,m2.b)); 35 } 36 } 37 if(error) printf("error\n"); else printf("%d\n",ans); 38 } 39 return 0; 40 }
Matrix Chain Multiplication(表达式求值用栈操作)
标签:
原文地址:http://www.cnblogs.com/shanyr/p/5200606.html