uva442 Matrix Chain Multiplication

UVA 442

题意:输入几个矩阵
然后输入字符串,根据输出的字符串,判断矩阵相乘所需要计算的乘法次数

思路:用栈的思想,用一个二维数组模拟栈,遇到左括号往上多一层,遇到右括号运算结果,保存到下一层中,计算到字符串末尾。每次计算结果,把乘法次数加上去,最后得到的就是总次数

代码:
#include <iostream>
using namespace std;
#include <stdio.h>
#include <string.h>
struct SB
{
    int x;
    int y;
} sb[30];

struct SBB
{
    int x;
    int y;
}sbb[30];
char str[1005];
char stack[1005][1005];
int main()
{
    int n;
    while (scanf("%d", &n) != EOF)
    {
	getchar();
	int a,b;
	char c;
	memset(sb, 0, sizeof(sb));
	memset(stack, 0, sizeof(stack));
	for (int i = 0; i < n; i ++)
	{
	    scanf("%c%d%d",&c, &a, &b);
	    int nu = c - 'A';
	    sb[nu].x = a;
	    sb[nu].y = b;
	    getchar();
	}
	while(gets(str) != NULL)
	{
	    memset(sbb, 0, sizeof(sbb));
	    for (int i = 0; i < 26; i ++)
	    {
		sbb[i].x = sb[i].x;
		sbb[i].y = sb[i].y;
	    }
	    int bo = 0;
	    int sum = 0;
	    memset(stack, 0, sizeof(stack));
	    int t = 0;
	    int k = 0;
	    int lenstr = strlen(str);
	    for (int i = 0; i < lenstr; i ++)
	    {	
		if (str[i] == '(')
		{  
		    t ++;
		    k = strlen(stack[t]);
		}
		else if(str[i] == ')')
		{
		    t --;
		    k = strlen(stack[t]);
		    strcpy(stack[t] + k, stack[t + 1]);
		    k = strlen(stack[t]);
		    stack[t + 1][0] = '\0';
		}
		else
		{
		    stack[t][k++] = str[i];
		    stack[t][k] = '\0';
		}
		if (k == 2)
		{
		    int aa = stack[t][0] - 'A';
		    int bb = stack[t][1] - 'A';
		    if(sbb[aa].y != sbb[bb].x)
		    {
			bo = 1;	
			printf("error\n");
			break;
		    }
		    else
		    {
			sum += sbb[aa].x * sbb[aa].y * sbb[bb].y;
			sbb[aa].y = sbb[bb].y;
			k = 1;
			stack[t][k] = '\0';
		    }
		}
	    }	    
	    if (bo == 0)
		printf("%d\n", sum);
	}
    }
    return 0;
}



你可能感兴趣的:(ACM,uva)