UVA - 442 Matrix Chain Multiplication(栈模拟水题+专治自闭)

题目:

给出一串表示矩阵相乘的字符串,问这字符串中的矩阵相乘中所有元素相乘的次数。

思路:

遍历字符串遇到字母将其表示的矩阵压入栈中,遇到‘)’就将栈中的两个矩阵弹出来,然后计算这两个矩阵的元素相乘的次数,累加就可以了。

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;
}

猜你喜欢

转载自www.cnblogs.com/sykline/p/10447751.html