• 矩阵连乘的相乘次数(ZOJ1094)


    题目链接:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=94

    解题报告:

    1、数据结构:

    ///矩阵行数和列数
    struct Node{
        int r;
        int c;
    };
    
    ///矩阵的属性
    map <string,Node> matrix;
    
    ///模拟矩阵相乘
    stack <Node> array;
    
    ///读取消息
    string exp;

    2、模拟矩阵相乘。

    ①遇到矩阵进栈array;

    ②遇到')'出栈两个矩阵,相乘,得到新的矩阵,然后进栈。

    ③记录相乘次数。

    #include <iostream>
    #include <string>
    #include <string.h>
    #include <algorithm>
    #include <stack>
    #include <map>
    
    using namespace std;
    
    ///矩阵的行数和列数
    struct Node
    {
        int row;
        int col;
    };
    
    ///矩阵参数
    map<char,Node> matrix;
    
    int n;///矩阵个数
    char name;///矩阵名称
    
    int main()
    {
    
        ///读取数据
        cin>>n;
        for(int i=0; i<n; i++)
        {
            cin>>name;
            cin>>matrix[name].row>>matrix[name].col;
        }
    
        ///计算矩阵
        string exp;
    
        ///对每一个矩阵计算
        while(cin>>exp)
        {
            int i;///矩阵做乘法的次数
            int Count=0;
            stack<Node>array;///模拟矩阵的乘法
            for(i=0; i<exp.size(); i++)
            {
                if(exp[i]=='(') continue;
                ///遇到右括号
                if(exp[i]==')')
                {
                    Node b=array.top();
                    array.pop();
                    Node a=array.top();
                    array.pop();
                    if(a.col!=b.row)
                    {
                        cout<<"error"<<endl;
                        break;
                    }
                    ///累计两个矩阵相乘的次数
                    Count+=a.row*b.row*b.col;
                    ///将计算到的新矩阵如栈
                    Node tmp= {a.row,b.col};
                    array.push(tmp);
                }
                else array.push(matrix[exp[i]]);   ///矩阵如栈
            }
            if(i==exp.size())
            {
                cout<<Count<<endl;
            }
        }
        return 0;
    }
  • 相关阅读:
    CSS基础
    AXIS2 开发笔记
    Tomcat和Weblogic下ajax或get中文乱码
    Jetty和Tomcat的选择:按场景而定
    分页
    windows linux 下,获取java项目绝对路径的方法
    oracle SQL
    ArrayUtils
    Xcode 调试技巧
    Core Data持久化数据存储(1)
  • 原文地址:https://www.cnblogs.com/TreeDream/p/5319022.html
Copyright © 2020-2023  润新知