题意很好理解,需要用到栈去模拟元素的删除和添加。
声明一个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;
}