`
java-mans
  • 浏览: 11445870 次
文章分类
社区版块
存档分类
最新评论

442 - Matrix Chain Multiplication***

 
阅读更多
//题目刚做是思路出现了问题,栈中元素只需要row 和column 即可。
//字典可以包含一个char,但更好的做法是将char型转换成下标
//新函数append()
#include <iostream>
#include <string>
#include <cstdio>
#include <stack>
using namespace std;
struct Type
{
	int row;
	int column;
	Type():row(0),column(0){}
	Type(int a,int b):row(a),column(b){}
};
bool operator!=(const Type &a,const Type &b)//要定义成const型,否则编译出错
{
	return (a.column!=b.column || a.row!=b.row);//这里曾经出错,!=
}
int main()
{
	//freopen("data.in","r",stdin);
	//freopen("data.out","w",stdout);
	Type p[30];
	int n;
	cin>>n;
	for(int i=0;i<n;i++)
	{
		char ch;
		int a,b;
		cin>>ch>>a>>b;
		p[ch-'A'].row=a;
		p[ch-'A'].column=b;
	}
	string line;
	while(cin>>line)
	{		
		int num=0;
		stack<Type> s;
		line.insert(0,"(");//这里插入元素为字符串型
		line.append(")");
		int flag=1;
		for(int i=0;i<line.size() && flag==1;i++)
		{
			if(line[i]=='(')
			{
				s.push(Type(-1,0));
			}
			else if(line[i]==')')
			{
				Type t1,t2;
				if(!s.empty() && s.top()!=Type(-1,0))
				{
					t2=s.top();
					s.pop();
				}
				while(!s.empty() && s.top()!=Type(-1,0))
				{
					t1=s.top();
					if(t1.column!=t2.row)
					{
						printf("error\n");
						flag=0;
						break;
					}
					else
					{
						s.pop();
						num+=t1.row*t1.column*t2.column;
						t2.row=t1.row;
					}
				}
				s.pop();
				s.push(t2);
			}
			else 
			{
				s.push(p[line[i]-'A']);
			}
		}
		if(flag==1)
			printf("%d\n",num);
	}
	return 0;
}


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics