您的位置:首页 > 大数据 > 人工智能

UVa 442 - Matrix Chain Multiplication

2013-04-17 14:20 369 查看
  用栈进行模拟,读取字符串,然后逐个字符进行判断,是‘(’就忽略, 是大写字母的话入栈,是‘)’的话就弹出两个矩阵判断计算。

  代码如下:

#include <cstdio>
#include <cstring>
#include <cctype>
#include <stack>
#define MAXN 1000
using namespace std;

struct Matrix
{
int r;
int c;
} mat[26];

int main()
{
#ifdef LOCAL
freopen("in", "r", stdin);
#endif
int n;
scanf("%d", &n);
for (int i = 0; i < n; i++)
{
char s[10];
scanf("%s", s);
int ix = s[0] - 'A';
scanf("%d%d", &mat[ix].r, &mat[ix].c);
}
char s[MAXN];
while (scanf("%s", s) != EOF)
{
stack<Matrix> st;
int res = 0;
bool error = false;
int len = strlen(s);
for (int i = 0; i < len; i++)
{
if (s[i] == '(')   continue;
else if (isupper(s[i]))
{
int ix = s[i] - 'A';
Matrix t = (Matrix){mat[ix].r, mat[ix].c};
st.push(t);
}
else if (s[i] == ')')
{
Matrix b = st.top();
st.pop();
Matrix a = st.top();
st.pop();
if (a.c != b.r)
{
error = true;
break;
}
else
{
res += a.r * a.c * b.c;
Matrix t = (Matrix){a.r, b.c};
st.push(t);
}
}
}
if (error)   printf("error\n");
else printf("%d\n", res);
}
return 0;
}


Code 2
  不过也算是有点收获吧,复习了一下结构体,同时又被Matrix a = st.pop();坑了一把...然后就是,第一个代码只用了8ms,而这个却用了22ms,差到哪里去了呢?感觉也差多少啊                                                                -- 2013.7.8
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: