uva 442 Matrix Chain Multiplication
来源:互联网 发布:c语言嵌入式开发 编辑:程序博客网 时间:2024/06/16 14:26
如果遇到 ‘(’ 或字母 的话把它压栈,同时用一个op变量记录它是括号还是操作数。当遇到‘)’时一直出栈,直到出栈元素为‘(’。
特别的,如果输入的是"ABC"这样没有括号的串的话,可以先对串进行预处理,即叫上左右括号,同时记得加上字符串结尾标志'\0'。
#include <iostream>#include<stdio.h>#include<stack>#include<cstring>using namespace std;typedef struct { int r,c;}Matrix; //原始输入的矩阵A~Ztypedef struct { int op; //括号为0,操作数为1 long long r,c; //相乘结果很大,记得用long long存}Node; //要压栈的矩阵stack<Node>node;stack<Node>temp_node;Matrix m[50];char s[200];int main(){ int n; int num ; bool ok ; long long ans ; scanf("%d",&n); while(!node.empty()) node.pop(); for(int i = 0; i < n;i++) { getchar(); char ch = getchar(); scanf("%d %d",&m[ch - 'A'].r,&m[ch - 'A'].c); } while(scanf("%s",s + 1)!=EOF) //对输入串进行预处理,左右加上括号 { //所以对输入从s+1开始保存,s[0]为左括号 s[0] = '('; int len = strlen(s); s[len ] = ')'; s[len + 1] = '\0'; ans = 0; ok = true; num = 0; for(int i = 0; i < strlen(s);i++) //注意此处的strlen(s)与len是不同的 { if(s[i] == '(') { Node temp; temp.op = 0; node.push(temp); } else if(s[i] == ')') { while(true) { Node temp = node.top(); node.pop(); if(temp.op == 0) break; //出栈至左括号 else { temp_node.push(temp); //把非括号元素压入另一个暂存栈中 //相当于把顺序再颠倒为原来输入时的顺序 num++; //记录暂存栈中的元素个数 } } while(num > 1) { Node temp1 = temp_node.top(); temp_node.pop(); Node temp2 = temp_node.top(); temp_node.pop(); num-= 2; if(temp1.c == temp2.r) { ans += temp1.r * temp1.c * temp2.c; temp1.c = temp2.c; //改变列数再压栈 temp_node.push(temp1); num++; } else { ok = false; break; } } if(!ok) break; node.push(temp_node.top()); temp_node.pop(); num--; } else //读入的是非括号元素 { Node temp; temp.op = 1; temp.r = m[s[i] - 'A'].r; temp.c = m[s[i] - 'A'].c; node.push(temp); } } if(ok) printf("%lld\n",ans); else printf("error\n"); } return 0;}
0 0
- UVa 442 Matrix Chain Multiplication
- Uva 442 Matrix Chain Multiplication
- UVa 442 Matrix Chain Multiplication
- uva 442 - Matrix Chain Multiplication
- UVa 442 - Matrix Chain Multiplication
- UVa 442 - Matrix Chain Multiplication
- UVa 442 Matrix Chain Multiplication
- UVA 442 Matrix Chain Multiplication
- uva 442 - Matrix Chain Multiplication
- uva 442 Matrix Chain Multiplication
- UVa 442 - Matrix Chain Multiplication
- UVa 442 - Matrix Chain Multiplication
- uva 442Matrix Chain Multiplication
- uva-442 Matrix Chain Multiplication
- UVa 442 - Matrix Chain Multiplication
- uva 442 - Matrix Chain Multiplication
- UVA 442 Matrix Chain Multiplication
- uva 442 Matrix Chain Multiplication
- sql exec 参数的传递
- POJ 1328 - Radar Installation(贪心)
- Wi-Fi与IEEE 802.11系列标准关系
- 用Blend设计样式
- List容器内存分配原则
- uva 442 Matrix Chain Multiplication
- C#.Net操作注册表RegistryKey
- FindWindow用法
- 安卓adb remount失败时,报failed: Operation not permitted
- struts2 junit plugin的使用
- 黑马程序员_交通灯系统
- 二分查找总结
- gtest->编译
- Ext store reload load 传参问题