Matrix Chain Multiplication 矩阵链乘 UVA 442

解题思路:首先解决如何保存输入字母所对应的两个值,通过定义结构体数组nt[0]表示字符'A',以此类推;然后通过通过栈来储存输入的字母,遇到")"时出栈两个元素做运算("("  ")"不入栈)。

  1. #include<cstdio>
  2. #include<stack>
  3. #include<iostream>
  4. #include<string>
  5. using namespace std;
  6. struct note{
  7.     int a,b;
  8.     note (int a1=0,int b1=0):a(a1),b(b1){}
  9. }nt[30];
  10. stack<note>st;
  11. int main(){
  12.     int n;
  13.     scanf("%d",&n);
  14.     for(int i=0;i<n;i++)
  15.     {   
  16.         getchar();                       //吃掉换行,否则会错 
  17.         char ch;
  18.         scanf("%c",&ch);
  19.         int t=ch-'A';
  20.         scanf("%d%d",&nt[t].a,&nt[t].b);
  21.     }
  22.     string str;
  23.     while(cin>>str){
  24.         int flag=1;
  25.         int sum=0;
  26.         for(int i=0;i<str.length();i++){
  27.             if(isalpha(str[i]))st.push(nt[(str[i]-'A')]);
  28.             else if(str[i]==')'){
  29.                 note n1=st.top();st.pop();
  30.                 note n2=st.top();st.pop();
  31.                 if(n2.b==n1.a){
  32.                     sum+=n2.a*n2.b*n1.b;
  33.                     st.push(note(n2.a,n1.b));
  34.                 }
  35.                 else {
  36.                     flag=0;
  37.                     break;
  38.                 }
  39.             }
  40.         }
  41.         if(flag)printf("%d\n",sum);
  42.         else printf("error\n");
  43.     }
  44.     return 0;
  45. }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

柏油

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值