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

hdoj1082 Matrix Chain Multiplication(栈的运用)

2017-06-12 19:21 375 查看
来源:http://acm.hdu.edu.cn/showproblem.php?pid=1082

感觉自己做复杂了,还用了map。

代码如下:

#include<stdio.h>
#include<string>
#include<iostream>
#include<map>
#include<stack>
using namespace std;
struct matr
{
int m,n;
};
map<char,matr> alp;
int main()
{
matr temp,t1,t2,temp1;
char c;
int i,j,num,sum,k,flag;
char str[250];
stack<char>s1;
stack<char>s2;
scanf("%d",&num);
getchar();
for(i=0;i<num;i++)
{
scanf("%c%d%d",&c,&temp.m,&temp.n);
alp.insert(make_pair(c,temp));
getchar();
}
while(~scanf("%s",str))
{
int len;
sum=0;k=0;flag=0;
len=strlen(str);
if(len==1){printf("0\n");continue;}
while(!s1.empty())s1.pop();
while(!s2.empty())s2.pop();
for(i=0;i<len;i++)
{
if(str[i]=='(')s1.push(str[i]);
if(str[i]>='A'&&str[i]<='Z')s2.push(str[i]);//与!!!
if(str[i]==')')
{
s1.pop();
c=s2.top();s2.pop();
t2=alp[c];
c=s2.top();s2.pop();
t1=alp[c];
if(t1.n!=t2.m)
{
flag=1;
printf("error\n");break;
}
else
{
sum+=t1.m*t1.n*t2.n;
temp1.m=t1.m;
temp1.n=t2.n;
alp.insert(make_pair((char)k,temp1));
s2.push((char)k);k++;
}
}
}
for(i=0;i<k;i++) alp.erase((char)i);
if(flag==1)continue;
else printf("%d\n",sum);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  杭电 算法