UVAOJ 442 Matrix Chain Multiplication

    题意很好理解,需要用到栈去模拟元素的删除和添加。

声明一个tri【60】的数组(>2*26)是为了保存两个矩阵相乘后行数和列数信息,然后把新的信息入栈。

#include <iostream>
#include <iomanip>
#include <cstdio>
#include <set>
#include <vector>
#include <map>
#include <cmath>
#include <algorithm>
#include <memory.h>
#include <string>
#include <cstring>
#include <sstream>
#include <cstdlib>
#include <ctime>
#include <cassert>
using namespace std;
const int MAXN=30;
struct maxtri
{
    int r,c;
}tri[60];
char ask[100],stack[100];
int main()
{
   int n,i;
   scanf("%d",&n);getchar();//要注意吸收回车符
   for(i=1;i<=n;i++)
   {
       char ch;
       scanf("%c",&ch);
       scanf("%d%d",&tri[ch-'A'].r,&tri[ch-'A'].c);//方便O(1)的查找,所以不选择按顺序存储。
       getchar();//要注意吸收回车符
   }
   while(scanf("%s",ask)!=EOF)
   {
      int top=0,ok=1;
      long long  sum=0;//long long 好像有点必要
      int len=strlen(ask);
      int tmp;
      for(i=0;i<len;i++)
      {
          if(ask[i]!=')')  stack[++top]=ask[i]-'A';//入栈的都是int 型的数,且不大于26
          else
          {
             if(tri[stack[top-1]].c!=tri[stack[top]].r)  {ok=0;printf("error\n");break;}
             else
             {

                 sum+=tri[stack[top-1]].r*tri[stack[top-1]].c*tri[stack[top]].c;//计算相乘次数
                 tmp=stack[top-1]+26;//分配新的空间
                 tri[tmp].r=tri[stack[top-1]].r;//更新行信息
                 tri[tmp].c=tri[stack[top]].c;//更新列信息
                 top=top-3;//出栈三个元素
                 stack[++top]=tmp;//新的tmp入栈
                //printf("%lld %d %d %d %d\n",sum,tri[stack[top-1]].r,tri[stack[top-1]].c,tri[stack[top]].r,tri[stack[top]].c);
             }
          }
      }
      if(ok)  printf("%lld\n",sum);

   }
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值