标签:scanf AC 矩阵链乘 bre exp space col cstring matrix
题目链接:
https://cn.vjudge.net/problem/UVA-442
1 /* 2 问题 3 输入有括号表示优先级的矩阵链乘式子,计算该式进行的乘法次数之和 4 5 解题思路 6 栈的应用,直接忽视左括号,每次只计算栈顶的两个矩阵会更加方便。 7 */ 8 #include<cstdio> 9 #include<cstring> 10 #include<stack> 11 #include<cctype> 12 using namespace std; 13 struct MAT{ 14 int r,c; 15 }mat[26]; 16 17 char exp[10100]; 18 stack<MAT> s; 19 int main() 20 { 21 //freopen("E:\\testin.txt","r",stdin); 22 char tc; 23 int t1,t2,n,i; 24 while(scanf("%d",&n) != EOF){ 25 for(i=0;i<26;i++){ 26 mat[i].r=0; 27 mat[i].c=0; 28 } 29 for(i=0;i<n;i++){ 30 scanf(" %c%d%d",&tc,&t1,&t2); 31 mat[tc-‘A‘].r=t1; 32 mat[tc-‘A‘].c=t2; 33 } 34 35 while(scanf(" %s",exp) != EOF){ 36 long long ans=0; 37 int err=0; 38 int len=strlen(exp); 39 for(i=0;i<len;i++){ 40 if(isalpha(exp[i])){ 41 s.push(mat[exp[i]-‘A‘]); 42 }else if(exp[i] == ‘)‘){ 43 struct MAT m2=s.top();s.pop(); 44 struct MAT m1=s.top();s.pop(); 45 if(m1.c != m2.r){ 46 err=1; 47 break; 48 } 49 ans += m1.r*m2.r*m2.c; 50 struct MAT tmp; 51 tmp.r=m1.r; 52 tmp.c=m2.c; 53 s.push(tmp); 54 } 55 } 56 57 if(err) 58 printf("error\n"); 59 else 60 printf("%lld\n",ans); 61 while(!s.empty()){ 62 s.pop(); 63 } 64 } 65 } 66 return 0; 67 }
UVa 442 Matrix Chain Multiplication(栈的应用)
标签:scanf AC 矩阵链乘 bre exp space col cstring matrix
原文地址:https://www.cnblogs.com/wenzhixin/p/9129786.html