hdoj1082 Matrix Chain Multiplication(棧的運用)

來源: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;
}


發佈了96 篇原創文章 · 獲贊 7 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章