题意:计算给出的表达式需要多少步?
思路:矩阵乘法
[n,m]∗[m,k]=[n,k]
,需要
n∗m∗k
步。把中缀表达式转成后缀表达式,这个题目的转换有一种讨巧的方法,直接把’)’换成’*’即可,注意需要把这个式子反一下来计算。然后来解这个逆波兰式即可。解逆波兰式的原则,如果碰到的符号,就用这个符号计算栈顶的两个数,然后把结果入栈。如果碰到数字,直接入栈。
http://acm.hdu.edu.cn/showproblem.php?pid=1082
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <cmath>
#include <ctime>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#define rep(i,a,b) for(int i = (a) ; i <= (b) ; i ++)
#define rrep(i,a,b) for(int i = (b) ; i >= (a) ; i --)
#define repE(p,u) for(Edge * p = G[u].first ; p ; p = p -> next)
#define cls(a,x) memset(a,x,sizeof(a))
#define eps 1e-8
using namespace std;
const int MOD = 1e9+7;
const int INF = 0x3f3f3f3f;
const int MAXN = 1e5+5;
const int MAXE = 2e5+5;
typedef long long LL;
typedef unsigned long long ULL;
int T,n,m,k;
int fx[] = {0,1,-1,0,0};
int fy[] = {0,0,0,-1,1};
struct Node {
int x,y;
Node(){}
Node(int _x,int _y) {x = _x ; y = _y;}
}A[30];
stack<char>s1,s2;
stack<Node>ANS;
void input() {
scanf("%d",&n);
char tmpc[10];
int tmpx,tmpy;
rep(i,1,n) {
scanf("%s %d %d",tmpc,&tmpx,&tmpy);
A[tmpc[0]-'A'].x = tmpx;
A[tmpc[0]-'A'].y = tmpy;
}
}
char a[1005];
void solve() {
while(~scanf("%s",a)) {
while(!s1.empty())s1.pop();
while(!s2.empty())s2.pop();
while(!ANS.empty())ANS.pop();
int lena = strlen(a);
rep(i,0,lena-1) {
if(a[i]==')') {
s1.push('*');
}
else if(a[i] >= 'A' && a[i] <= 'Z'){
s1.push(a[i]);
}
}
while(!s1.empty()) {
s2.push(s1.top());
s1.pop();
}
int ans = 0;
int err = 0;
while(!s2.empty()) {
char tmpc = s2.top();
s2.pop();
if(tmpc >= 'A' && tmpc <= 'Z') {
ANS.push(A[tmpc-'A']);
}
else {
Node tmp2 = ANS.top();ANS.pop();
Node tmp1 = ANS.top();ANS.pop();
if(tmp1.y != tmp2.x) { err = 1 ; break ; }
Node tmp = Node(tmp1.x,tmp2.y);
ans += tmp1.x * tmp1.y * tmp2.y;
ANS.push(tmp);
}
}
if(err) {
puts("error");
}
else {
printf("%d\n",ans);
}
}
}
int main(void) {
input();
solve();
return 0;
}