粗心!水题WA了。。
WA:
//break; 这里如果不停止循环,后面如果再次出现 矩阵无法相乘的情况, 就会多次输出error; 如((AC)B)
#include<stdio.h>
#include<string.h>
#include<ctype.h>
int matrices[1000][2];
int stack[10000];
char temp[10000];
int main()
{
//
freopen("input.txt","r",stdin);
int numma;
scanf("%d\n", &numma);
//ch-'A'
for(int i = 0; i < numma; i++)
{
int index = getchar()-'A';
scanf("%d", &matrices[index][0]);
scanf("%d\n", &matrices[index][1]);
}
while(scanf("%s", temp) == 1)
{
int top= 0;
int sum = 0;
int idres = 'Z'+1;
bool flag = false;
for(int i = 0; i < strlen(temp); i++)
{
if(temp[i] == '(')
//continue;
stack[top++] = '(';
else if(isalpha(temp[i]))
stack[top++] = temp[i];
else if(temp[i] == ')')
{
if(top <3)
{
flag = true;
printf("error\n");
break;
}
int ch1 = stack[top-2]-'A';
int ch2 = stack[top-1]-'A';
if(matrices[ch1][1] != matrices[ch2][0])
{
flag = true;
printf("error\n");
//break;
}
else
{
sum += matrices[ch1][0]*matrices[ch1][1]*matrices[ch2][1];
top = top -3;
stack[top++] = idres;
matrices[idres-'A'][0]= matrices[ch1][0];
matrices[idres-'A'][1]= matrices[ch2][1];
idres++;
}
}
}
if(flag) continue;
else
{
printf("%d\n", sum);
}
}
}
AC:
以防万一,尽量在循环后统一输出
#include<stdio.h>
#include<string.h>
#include<ctype.h>
int matrices[1000][2];
int stack[10000];
char temp[10000];
int main()
{
//
freopen("input.txt","r",stdin);
int numma;
scanf("%d\n", &numma);
//ch-'A'
for(int i = 0; i < numma; i++)
{
int index = getchar()-'A';
scanf("%d", &matrices[index][0]);
scanf("%d\n", &matrices[index][1]);
}
while(scanf("%s", temp) == 1)
{
int top= 0;
int sum = 0;
int idres = 'Z'+1;
bool flag = false;
for(int i = 0; i < strlen(temp); i++)
{
if(temp[i] == '(')
//continue;
stack[top++] = '(';
else if(isalpha(temp[i]))
stack[top++] = temp[i];
else if(temp[i] == ')')
{
if(top <3)
{
flag = true;
break;
}
int ch1 = stack[top-2]-'A';
int ch2 = stack[top-1]-'A';
if(matrices[ch1][1] != matrices[ch2][0])
{
flag = true;
break;
}
else
{
sum += matrices[ch1][0]*matrices[ch1][1]*matrices[ch2][1];
top = top -3;
//
stack[top++] = idres;
matrices[idres-'A'][0]= matrices[ch1][0];
matrices[idres-'A'][1]= matrices[ch2][1];
idres++;
}
}
}
if(flag)
{
printf("error\n");
}
else
{
printf("%d\n", sum);
}
}
}