题意:一直矩阵的行和列,求给出的矩阵乘法表达式要做多少次基本元素的乘法。
分析:stack的应用。
1、格式控制题目已给出说明,<CR>是回车符。开始判断的时候习惯性的以' \0 '
作为字符串的结束标志。
2、开始没用stack,用了静态链表,发现有些地方很难控制。
3、复习了矩阵乘法的特性。
4、数组存每组的信息时,因为多次使用,千万不能忘记清0。
STL中的stack
#include<cstdio>
#include<iostream>
#include<cstring>
#include<stack>
#include<cctype>
using namespace std;
typedef struct node
{
char name;
int x,y;
}mattype;
stack<char> s1;
stack<mattype> s2;
mattype mat[30];
int main()
{
char a[100];
int n,i,ans;
bool flag;
mattype m;
scanf("%d\n",&n);
for(i=0;i<n;i++)
scanf("%c%d%d\n",&mat[i].name,&mat[i].x,&mat[i].y);
memset(a,0,sizeof(a));
while(fgets(a,100,stdin)!=NULL)
{
ans=0,flag=true;
for(i=0;a[i]!='\n';i++)
{
if(isalpha(a[i]))
s2.push(mat[a[i]-'A']);
else if(a[i]=='(')
s1.push(a[i]);
else
{
s1.pop();
m=s2.top();
s2.pop();
if(m.x!=s2.top().y)
flag=false;
else
{
ans+=s2.top().x*m.x*m.y;
s2.top().y=m.y;
}
}
}
if(flag==false)
printf("error\n");
else printf("%d\n",ans);
memset(a,0,sizeof(a));
}
return 0;
}
//<CR>是换行符,即回车‘\n'
#include<cstdio>
#include<cctype>
#include<cstring>
using namespace std;
typedef struct node
{
char name;
int x,y;
}mattype;
int main()
{
mattype mat[30],stack2[30];
char a[100],stack1[30];
int ans,flag,p,p1,p2,n,i;
scanf("%d\n",&n);
for(i=0;i<n;i++)
scanf("%c%d%d\n",&mat[i].name,&mat[i].x,&mat[i].y);
memset(a,0,sizeof(a));
while(fgets(a,100,stdin)!=NULL)
{
ans=0,flag=true;
p=0,p1=0,p2=0;
for(i=0;a[i]!='\n';i++)
{
if(isalpha(a[i]))
stack2[p2++]=mat[a[i]-'A'];
else if(a[i]=='(')
stack1[p1++]=a[i];
else
{
p1--;
p2--;
if(stack2[p2].x!=stack2[p2-1].y)
flag=false;
else
{
ans+=stack2[p2-1].x*stack2[p2].x*stack2[p2].y;
stack2[p2-1].y=stack2[p2].y;
}
}
}
if(flag==false) printf("error\n");
else printf("%d\n",ans);
memset(a,0,sizeof(a));
}
return 0;
}