uva-442-矩陣鏈乘

來源:互聯網
上載者:User

標籤: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;}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.