HDU 1082 Matrix Chain Multiplication

题目地址:点击打开链接

思路:用map和stack即可解决

AC代码:

#include<iostream>
#include<map>
#include<string>
#include<stack>

using namespace std;

struct node{int row,col;};

int main()
{
	int n,i,count;
	char c;
	map<char,node> mar;
	cin>>n;
	for(i=0; i<n; i++)
	{
		cin>>c;
		cin>>mar[c].row>>mar[c].col;
	}
	string s;
	while(cin>>s)
	{
		count = 0;
		stack<node> array;
		for(i=0; i<s.size(); i++)
		{
			if(s[i] == '(')
				continue;
			if(s[i] == ')')
			{
				node a = array.top();
				array.pop();
				//cout<<a.row<<" "<<a.col<<endl;
				node b = array.top();
				//cout<<b.row<<" "<<b.col<<endl;
				array.pop();
				/*if(a.col != b.row)
				{
					cout<<"error"<<endl;
					break;
				}*/
				if(a.row != b.col)//要注意栈的性质,先进后出
				{
					cout<<"error"<<endl;
					break;
				}
				count += b.row * b.col * a.col;
				//node temp = {a.row,b.col};//这也要改
				node temp = {b.row,a.col};
				array.push(temp);
			}
			else
			{
				array.push(mar[s[i]]);
			}
		}
		if(i == s.size())
			cout<<count<<endl;
	}
	return 0;
}


你可能感兴趣的:(HDU 1082 Matrix Chain Multiplication)