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

来源:互联网 发布:java 源代码文件 混淆 编辑:程序博客网 时间:2024/06/06 17:28
#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];}elsekong = 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);elseprintf("error\n");}return 0;}

0 0