1. 程式人生 > >UVA - 442 Matrix Chain Multiplication(棧模擬水題+專治自閉)

UVA - 442 Matrix Chain Multiplication(棧模擬水題+專治自閉)

error color class sin open style else tdi return

題目:

給出一串表示矩陣相乘的字符串,問這字符串中的矩陣相乘中所有元素相乘的次數。

思路:

遍歷字符串遇到字母將其表示的矩陣壓入棧中,遇到‘)’就將棧中的兩個矩陣彈出來,然後計算這兩個矩陣的元素相乘的次數,累加就可以了。

PS:註意彈出的矩陣表示的先後順序。

代碼:

#include <bits/stdc++.h>
#define inf 0x3f3f3f3f
#define MAX 1000000000
#define mod 1000000007
#define FRE() freopen("in.txt","r",stdin)
#define FRO() freopen("out.txt","w",stdout)
using
namespace std; typedef long long ll; typedef pair<int,int> P; const int maxn = 27; int n; struct MAT{ int x,y; }mat[maxn]; int main(){ //FRE(); cin>>n; for(int i=0; i<n; i++){ char id; int x,y; cin>>id>>x>>y; mat[id
-A].x = x; mat[id-A].y = y; } // for(int i=0; i<26; i++){ // cout<<mat[i].x<<" "<<mat[i].y<<endl; // } string str; stack<MAT> sta; while(cin>>str){ int ans=0,ok=0; for(int i=0; i<str.length(); i++){
if(isupper(str[i])){ sta.push(mat[str[i]-A]); }else if(str[i]==)){ MAT t1 = sta.top();sta.pop(); MAT t2 = sta.top();sta.pop(); //cout<<t1.x<<" FUCK "<<t1.y<<" FUCK "<<t2.x<<" FUCK "<<t2.y<<endl; if(t1.x!=t2.y){//註意彈出來的兩個矩陣的先後順序(棧的特點) ok = 1; break; } ans += t2.x*t2.y*t1.y;//計算元素相乘的次數並累加 sta.push(MAT{t2.x,t1.y}); } } if(ok){ cout<<"error"<<endl; }else{ cout<<ans<<endl; } while(!sta.empty())sta.pop(); } return 0; }

UVA - 442 Matrix Chain Multiplication(棧模擬水題+專治自閉)