也是stack的用法
將 Matrix struct 宣告陣列來儲存A~Z的矩陣
遇到字母則push進堆疊,遇右括弧則pop兩個相乘再push
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <cstdio>
#include <cstdlib>
#include <string>
#include <iostream>
#include <stack>
using namespace std;
struct Matrix{
char name;
int row, col;
};
int main(){
int n;
Matrix mat[26]; //存放矩陣結構的陣列
stack<Matrix> s; //存放矩陣的堆疊
scanf("%d",&n);
getchar();
for(int i=0;i<n;i++){ //Input Matrixs
char a;
int r,c;
scanf("%c %d %d",&a,&r,&c);
getchar();
mat[a-'A'].name = a;
mat[a-'A'].row = r;
mat[a-'A'].col = c;
}
char input[1000];
while(fgets(input,sizeof(input),stdin)){
int count=0;
bool error=0;
for(int i=0;i<=strlen(input);i++){
if(isalpha(input[i])){ //找到字母則入堆疊
s.push(mat[input[i]-'A']);
}
else if(input[i]==')'){
Matrix mat_b = s.top(); s.pop();
Matrix mat_a = s.top(); s.pop();
if(mat_a.col != mat_b.row){
error=1;
break;
}
count += mat_a.row * mat_a.col * mat_b.col;
Matrix tmp;
tmp.row = mat_a.row;
tmp.col = mat_b.col;
s.push(tmp);
}
}
if(error==1)printf("error\n"); else printf("%d\n",count);
}
return 0;
}
沒有留言:
發佈留言