大致题意:
计算数个矩阵乘法,需要相乘的次数。
思路:
2个矩阵m*n、n*l的数值矩阵A、B相乘,成绩存入m*l的数值矩阵C,相乘次数为m*n*l。
使用一个字符指针p,
1-@-当前字符为“(”,则字符指针+1,递归计算括号内表达式t1、t2,p+1。
若t1、t2行数不相等,失败标志error设为1; 否则计算相乘后的乘积矩阵t。[ t.rows ; t.cols ; t.mults ]
2-@-当前字符为字母,记下对应矩阵行列数,相乘次数设为0,p+1。
最后返回乘积矩阵t。
模拟栈处理。
#include<iostream>
#include<cstdio>
using namespace std;
typedef struct{
int mults, rows, cols;
}triple;
int rows[260], cols[260];
char e[100];
int p;
char error;
triple expr(){
triple t;
if(e[p] == '('){
triple t1, t2;
p++;
t1 = expr();
t2 = expr();
p++;
if(t1.cols != t2.rows)
error = 1;
t.rows = t1.rows;
t.cols = t2.cols;
t.mults = t1.mults + t2.mults + t1.rows * t1.cols * t2.cols;
}
else{
t.rows = rows[e[p]];
t.cols = cols[e[p]];
t.mults = 0;
p++;
}
return t;
}
int main(){
char c;
int i, n, ro, co;
triple t;
scanf("%d", &n);
getchar();
for(i = 0; i < n; i++){
scanf("%c%d%d", &c, &ro, &co);
getchar();
rows[c] = ro;
cols[c] = co;
}
while(~scanf("%s", &e)){
p = error = 0;
t = expr();
if(error)
puts("error");
else
printf("%d\n", t.mults);
}
return 0;
}