uva 442 Matrix Chain Multiplication 矩阵链乘(入门经典 例题 6 -3)

例题 6 -3
这题是刘汝佳紫书上的,我想给他的大部分题目的代码都写上注释,这样说明我会了。。。寒假过去1/3了,玩好了,开始刷题了!!!
这题是结构体 , 栈,表达式的巧妙组合。
结构体里的构造函数
matrix(int a = 0 , int b = 0) : a(a) , b(b) { }
这个构造函数的意思是,先将a和b初始化为0,若主函数里的调用函数中参数a和b不为零,则a = a ; b = b;
s.push(matrix(m1.a,m2.b));
这个对栈的操作就是。有个 matrix型的结构体,a = m1.a ;b = m2. b;将这个结构体压入栈中。

#include<cstdio>
#include<cstdlib>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<iomanip>
#include<set>
#include<stack>
#include<ctime>
#include<queue>
#define LOCAL
#define pi 3.1415926
#define e 2.718281828459
#define mst(a,b) memset(a,b,sizeof(a))
const int  INF = 0x3f3f3f3f;
const int maxn = 30000;
using namespace std;

struct matrix{//矩阵属性的结构体
  int a , b;//矩阵的长和宽
  matrix(int a = 0,int b = 0):a(a),b(b){}//构造函数,上面有我写的,我对这个的一部分理解
}m[26];

int main(){
    int n;
    string name;//字符串 name
    cin >> n;
    for(int i = 0; i < n; i++){
        cin >> name;
        int k = name[0] - 'A';//一般可以讲A,B,C,a,b,c等字母用数字代替,用来表示该名称下的数据结构更方便一些
        cin  >>  m[k].a >>  m[k].b;
    }
    string ex;
    while(cin >> ex){
        stack<matrix>s;//申明一个栈。里面的存储类型是结构体的类型
        int len = ex.length();//字符串的测长度的函数
        bool t = false;
        int ans = 0;
        for(int i = 0; i < len; i++){
            if(isalpha(ex[i])) s.push(m[ex[i] - 'A']);//是字母就压入栈中
            else if(ex[i] == ')'){//这样的解析表达式一般只对‘)’进行处理,更方便一些
                matrix m2 = s.top(); s.pop();
                matrix m1 = s.top(); s.pop();//把栈顶的两个元素全部取出来,并用相同的结构体存储
                if(m1.b != m2.a) {t = true; break;}
                  ans+= m1.a * m2.a * m2.b;
                s.push(matrix(m1.a,m2.b));//使用构造函数,将新组建的结构压入栈中
            }
        }
        if(t) cout << "error" << endl;
        else cout << ans <<endl;
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值