Matrix Chain Multiplication 矩阵链乘 UVA 442
解题思路:首先解决如何保存输入字母所对应的两个值,通过定义结构体数组nt[0]表示字符’A’,以此类推;然后通过通过栈来储存输入的字母,遇到”)”时出栈两个元素做运算(”(“ “)”不入栈)。
- #include
- #include
- #include
- #include
- using namespace std;
- struct note{
- int a,b;
- note (int a1=0,int b1=0):a(a1),b(b1){}
- }nt[30];
- stack
st; - int main(){
- int n;
- scanf(“%d”,&n);
- for(int i=0;i<n;i++)
- {
- getchar(); //吃掉换行,否则会错
- char ch;
- scanf(“%c”,&ch);
- int t=ch-‘A’;
- scanf(“%d%d”,&nt[t].a,&nt[t].b);
- }
- string str;
- while(cin>>str){
- int flag=1;
- int sum=0;
- for(int i=0;i<str.length();i++){
- if(isalpha(str[i]))st.push(nt[(str[i]-‘A’)]);
- else if(str[i]==’)’){
- note n1=st.top();st.pop();
- note n2=st.top();st.pop();
- if(n2.b==n1.a){
- sum+=n2.a*n2.b*n1.b;
- st.push(note(n2.a,n1.b));
- }
- else {
- flag=0;
- break;
- }
- }
- }
- if(flag)printf(“%d\n”,sum);
- else printf(“error\n”);
- }
- return 0;
- }
还没有评论,来说两句吧...