UVA 442 (暑期-线性表-F-Matrix Chain Multiplication)

#include <cstdio>
#include <cstring>

int main() {
	int n, arr[30][10];
	scanf("%d", &n);
	getchar();
	//读入矩阵
	for (int i = 0; i < n; i++) {
		char c = getchar() - 'A';
		scanf("%d%d", &arr[c][0], &arr[c][1]);
		getchar();
	}
	char str[400];
	//读入式子
	while (gets(str)){
		int brr[400][3] = {0}, count = 0, len = strlen(str), sum = 0, kong = 1;
		for (int i = 0; i < len; i++) {
			if (str[i] == ')') {    //出栈
				//寻找左括号
				for (int j = count-1; j >=0 ; j--)
					if (brr[j][2] == '(' ) {
						int k;
						for (k = j+1; k+1 < count; k++) {
							//判断是否可以相乘
							if (brr[k][1] == brr[k+1][0]) {
								sum += brr[k][0] * brr[k][1] * brr[k+1][1];
								brr[k+1][0] = brr[k][0];
							}
							else
								kong = 0;
						}
						//合并完后左移
						brr[j][2] = brr[k][2];
						brr[j][0] = brr[k][0];
						brr[j][1] = brr[k][1]; 
						count = j + 1;
						break;
					}
			}
			// 入栈
			else { 
				brr[count][0] = arr[str[i]- 'A'][0];
				brr[count][1] = arr[str[i]- 'A'][1];
				brr[count][2] = str[i];
				count++;
			}
		}
		if (kong)
			printf("%d\n", sum);
		else
			printf("error\n");
	}
	return 0;
}

你可能感兴趣的:(UVA 442 (暑期-线性表-F-Matrix Chain Multiplication))