矩阵乘法计算量估算

当使用stack等stl库时,如果使用s.pop(),s.top(),则必须判定stack是否为空。

#include<iostream>
#include<vector>
#include<stack>
#include<string.h>
using namespace std;

int main()
{
    int num;
    vector<int> vrow;
    vector<int> vcol;
    cin>>num;

    for(int i=0; i<num; i++)
    {
        int x,y;
        cin>>x>>y;
        vrow.push_back(x);
        vcol.push_back(y);
    }

    char str[100];
    cin>>str;

    int siz = strlen(str);

    int count = 0;

    stack<char> s;
    for(int i=0; i<siz; i++)
    {
        if(str[i] >='A' && str[i]<='Z')
        {
            if(s.empty() || (!s.empty() && s.top()=='(') )
            {
                s.push(str[i]);
            }
            else
            {
                char ch = s.top();

                int r = vrow[ch-'A'];
                int p = vcol[ch-'A'];
                int c = vcol[str[i]-'A'];
                count = count + r*p*c;

                vrow[ch-'A'] = r;
                vcol[ch-'A'] = c;
            }
        }
        else if(str[i]==')')
        {
            char ch = s.top();

            s.pop();
            s.pop();
            if(!s.empty())
            {
                char ch2 = s.top();
                if(ch2>='A' && ch2<='Z')
                {
                    s.pop();

                    int m = vrow[ch2-'A'];
                    int p = vcol[ch2-'A'];
                    int n = vcol[ch-'A'];
                    count += m*p*n;

                    vrow[ch2-'A'] = m;
                    vcol[ch2-'A'] = n;

                    s.push(ch2);
                }
                else
                {
                    s.push(ch);
                }
            }
            else
            {
                s.push(ch);
            }
        }
        else if(str[i]=='(')
        {
            s.push(str[i]);
        }
        else
        {
        }
    }


    cout<<count;

    return 0;
}

  

posted @ 2016-12-30 17:08  Hardsoftware  阅读(898)  评论(0编辑  收藏  举报