UVa 442 - Matrix Chain Multiplication解题报告

来源:互联网 发布:圣诞快乐劳伦斯 知乎 编辑:程序博客网 时间:2024/06/17 00:11

利用栈模拟乘法括号运算。利用map建立键值映射可以很快的做出来。一次ac。

思路:用结构存储矩阵的row,col。然后用map把矩阵代号作为键值映射到结构上。遇到不是“)”的都压栈,遇到“)”就出栈计算,再建立新的映射存储新的矩阵压栈。

ps:@表示出错的地方

//442 - Matrix Chain Multiplication#include <iostream>#include <map>#include <cstring>#include <stack>using namespace std;struct nobe{int row, col;};int main(){//freopen("data.txt", "r", stdin);int N;cin >> N;getchar();map<char, nobe> s;for(int i = 0; i < N; i++)//数据录入,利用map建立映射{char c;cin >> c ;cin>> s[c].row >> s[c].col;}char str[100];getchar();while (cin.getline(str, 100)){int m = 0;s[m].col = 0, s[m].row = 0;//建立一个临时映射,存储AB的的col和rowint mul = 0, flag = 1;stack<int> st;for(int i = 0; i < strlen(str); i++){if(str[i] != ')')st.push(str[i]);else if(!st.empty()){char y = st.top();//@忘了栈是先进后出st.pop();char x = st.top();st.pop();st.pop();if(s[x].col != s[y].row){flag = 0;break;}mul += s[x].row * s[x].col * s[y].col;//s[m].row = s[x].row;//把AB的新矩阵存进去s[m].col = s[y].col;st.push(m++);}}if(flag)cout << mul << endl;elsecout << "error\n"; }return 0;}


0 0
原创粉丝点击