標籤:acm 棧的應用
<span style="font-size: 18px; ">思路:</span>
本題的關鍵在於解析運算式.本題的運算式比較簡單,可以用一個棧來完成--->>
遇到一個字母時,就入棧;遇到右括弧時就出棧進行計算,然後將新矩陣點入棧!
如果在這之間,如果A的列數不等於B的行數,則乘法無法進行!!!注意咯!
代碼如下:
#include<cstdio>#include<cstring>#include<iostream>#include<stack>#include<string>using namespace std;struct ma{ int h,l;//橫和列! ma(int l=0,int h=0):l(l),h(h) {}} m[26];int main(){ int n; cin>>n; for(int i=0; i<n; i++) { string name; cin>>name; cin>>m[name[0]-'A'].h>>m[name[0]-'A'].l; } string sen; while(cin>>sen) { stack<ma>Q; int flag=0,len=sen.length(); bool error=false; int ans=0; for(int i=0; i<len; i++) { if(isalpha(sen[i]))//如果是字母就入棧! Q.push(m[sen[i]-'A']); else if(sen[i]==')') { ma m2=Q.top();//倒數第一個! Q.pop(); ma m1=Q.top();//倒數第二個! Q.pop(); if(m1.h!=m2.l)//如果倒數第1個的橫長不等於倒數第1個的列長,則退出! { //即A的橫長!=B的列長! error=true; flag=1; break; } ans+=m1.h*m1.l*m2.h; Q.push(ma(m1.h,m2.l));//然後將建立的點入棧! } if(flag) break;//已經沒必要進行迴圈操作了! } if(error) cout<<"error"<<endl; else cout<<ans<<endl; } return 0;}