• UVA442 Matrix Chain Multiplication 矩阵运算量计算(栈的简单应用)


    栈的练习,如此水题竟然做了两个小时。。。

    题意:给出矩阵大小和矩阵的运算顺序,判断能否相乘并求运算量。

    我的算法很简单:比如(((((DE)F)G)H)I),遇到 (就cnt累计加一,字母入栈,遇到)减一,并出栈两个矩阵计算运算量,将计算后的矩阵压入栈。当cnt等于0时就输出运算量。

    难点是当不能运算后的处理。

    卡那么就其实主要是细节问题,最大的坑是里面退栈时倒着退出,没注意到结果每次计算都判断为不能计算。。。


    AC代码:

    #include <iostream>
    #include <cstdio>
    #include <stack>
    using namespace std;
    int const maxn = 27;
    
    struct Mat{
    	int x, y;
    };
    Mat mat[maxn];
    
    Mat multip(Mat a, Mat b) {
    	Mat tmp;
    	tmp.x = a.x;
    	tmp.y = b.y;
    	return tmp;
    }
    
    int main() {
    	int n, cnt = 0, kh = 0;
    	bool flag = true;
    	char tmp;
    	Mat a, b;
    	stack <Mat> v;
    	freopen("in", "r", stdin);
    	cin >> n;
    	while (n--) {
    		cin >> tmp;
    		tmp -= 'A';
    		cin >> mat[tmp].x >> mat[tmp].y;
    	}//while
    	while (cin >> tmp) {
    		if (kh == 0) {
    			flag = true;
    		}
    		if (flag == false) {
    			if (tmp == '(')
    				kh++;
    			else if (tmp == ')')
    				kh--;
    			continue;
    		}
    		if (tmp >= 'A' && tmp <= 'Z') {
    			v.push(mat[tmp - 'A']);
    		}//alpha
    		else{
    			if (tmp == '(') {
    				kh++;
    			}//(
    			else if (tmp == ')'){
    				kh--;
    				a = v.top();
    				v.pop();
    				b = v.top();
    				v.pop();
    				if (b.y != a.x) {
    					cout << "error" << endl;
    					cnt = 0;
    					flag = false;
    					continue;
    				}
    				cnt += b.x * a.x * a.y;
    				v.push(multip(b, a));
    			}//)
    		}//not alpha
    		if (kh == 0) {
    			cout << cnt << endl;
    			cnt = 0;
    		}//print
    	}//while 
    	return 0;
    }


    提交时又忘记去掉文件重定向了,wa了一下。。。

  • 相关阅读:
    python3-file的修改实现类似shell中sed的功能
    python3-字典的循环
    python3-file文件操作
    python3-字典的增删改查
    python3-字典中存储列表
    python3-字典中的一些常用方法
    python3-字典中包含字典
    报错调试和工具使用
    (三)、Struts第三天
    struts体系结构
  • 原文地址:https://www.cnblogs.com/java20130723/p/3212269.html
Copyright © 2020-2023  润新知