題意:一直矩陣的行和列,求給出的矩陣乘法表達式要做多少次基本元素的乘法。
分析: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;
}