UVa442矩阵连乘

粗心!水题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);
		}
	}
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值