题解 | #矩阵乘法计算量估算#

矩阵乘法计算量估算

https://www.nowcoder.com/practice/15e41630514445719a942e004edc0a5b

//用栈做吧
//遍历一遍输入的字符串就行,如果是'('入栈
//如果是字母就检测栈顶,如果栈顶是数字就做一次矩阵计算,栈顶是'('就入栈
//如果是')',弹出字母和'(',并检测栈顶,栈顶是数字就需要再做一次矩阵计算,栈顶是'('就入栈

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

int main(){
    int n;
    cin >> n;
    vector<vector<int>> vecinput(n,vector<int>(2,0));
    for(int i = 0;i<n;++i){
        cin >> vecinput[i][0] >> vecinput[i][1];
    }
    string inputstr;
    cin >> inputstr;
    stack<vector<int>> stmat;//矩阵栈
    int sum = 0;
    for(int i = 0;i<inputstr.size();++i){
        if(inputstr[i] == '('){
            stmat.push(vector<int>(1,0));
        }
        else if (inputstr[i] == ')'){
            vector<int> tmp = stmat.top();
            stmat.pop();
            stmat.pop();
            if(!stmat.empty()){
                if(stmat.top().size() == 2){
                    vector<int> tmptop = stmat.top();
                    sum += tmptop[0]*tmptop[1]*tmp[1];
                    stmat.pop();
                    tmptop[1] = tmp[1];
                    stmat.push(tmptop);
                }
                else{
                    stmat.push(tmp);
                }
            }
            else stmat.push(tmp);
        }
        else{
            if(stmat.empty())stmat.push(vecinput[inputstr[i]-'A']);
            else{
                if(stmat.top().size() == 1){//栈顶是左括号
                    stmat.push(vecinput[inputstr[i]-'A']);
                }
                else{//栈顶有数字
                    vector<int> tmp = stmat.top();
                    sum += tmp[0]*tmp[1]*vecinput[inputstr[i]-'A'][1];
                    stmat.pop();
                    tmp[1] = vecinput[inputstr[i]-'A'][1];
                    stmat.push(tmp);
                }
            }
        }
    }
    cout << sum << endl;
    return 0;
}

全部评论

相关推荐

友友们,我实在是不太明白,校招的话现在大多也是提前实习,然后转正也是需要考核的,考核通过才能转正,那这跟实习转正有什么区别啊
苦闷的仰泳鲈鱼刷了1...:提前实习,是让你提前熟悉业务的,后续是入职后可以减少试用期的(大部分是包入职的);转正实习,要是hc不够或者其他原因,让你正式offer可能都没有,这个风险很大。 ---个人看法和了解到的。
点赞 评论 收藏
分享
影04714:把图书管理系统那个项目经验内容适当的减少掉,然后改成据为己有不要说团队项目,因为图书管理系统这类常见的谁来了都能独立写出来,提问能圆过来即可
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务