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

紫书章六例题三 Matrix Chain Multiplication(stack)

2017-04-12 23:41 423 查看
好气啊,太粗心了,多了一个零也看不出来。扫到字母就进栈,否则就出栈计算。

#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <queue>
#include <vector>
#include <set>
#include <map>
#include <stack>
using namespace std;
struct node
{
int r,c;
node(int a=0,int b=0):r(a),c(b){}
};
node a[30];
int main()
{
//freopen("E:\\input.txt","r",stdin);
int n;
scanf("%d",&n);
for(int i=0;i<n;i++)
{
char c;
cin>>c;//scanf?
int k=c-'A';
scanf("%d %d",&a[k].r,&a[k].c);
}
getchar();//先读后面回车
string s;
while(getline(cin,s))
{
stack<node> sta;
int flag=0;
int ans=0;
int len=s.length();
for(int i=0;i<len;i++)
{
if(s[i]>='A'&&s[i]<='Z')
sta.push(a[s[i]-'A']);
else if(s[i]==')')
{
node k2=sta.top();sta.pop();
node k1=sta.top();sta.pop();
if(k1.c!=k2.r) {flag=1;break;}
ans+=k1.r*k1.c*k2.c;
sta.push(node(k1.r,k2.c));
}
}
if(flag) printf("error\n");
else printf("%d\n",ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: