hdu 1082 Matrix Chain Multiplication

 


Sample Input
   
   
   
   
9 A 50 10 B 10 20 C 20 5 D 30 35 E 35 15 F 15 5 G 5 10 H 10 20 I 20 25 A B C (AA) (AB) (AC) (A(BC)) ((AB)C) (((((DE)F)G)H)I) (D(E(F(G(HI))))) ((D(EF))((GH)I))
 

Sample Output
   
   
   
   
0 0 0 error 10000 error 3500 15000 40500 47500 15125
 
#include<stdio.h>
#include<string.h>
#include<iostream>
using namespace std;
const int N=10000;
/*
栈的模拟,集中精神,注意细节
*/
struct node
{
    char c;
    int x,y;
    node(char t='.',int a=0,int b=0){c=t;x=a;y=b;}
    void input(){scanf("%d%d",&x,&y);}
}p[27];
char s[2],m[N];
int solve()
{
    int top=1,i,k,j,len=strlen(m),res=0;
    node sta[N];
    sta[0].c=m[0];
	if(m[0]!='(')
		sta[0]=p[m[0]-'A'];
    for(i=1;i<len;++i)
    {
        if(m[i]=='(')
		{
            sta[top++].c=m[i];
		}
        else if(m[i]==')')
        {
			k=--top;
			sta[top-1]=sta[k];
			sta[top-1].c='*';
			k=top-2;
			if(k>-1&&sta[k].c!=')'&&sta[k].c!='(')
			{
				--top;
				if(sta[k].y!=sta[top].x)
					return -1;
				res+=sta[k].x*sta[k].y*sta[top].y;
				sta[k].y=sta[top].y;
				sta[k].c='*';
			}
        }
        else
		{
            k=m[i]-'A';
            if(sta[top-1].c=='('||sta[top-1].c==')')
            {
                sta[top].c='*';
                sta[top].x=p[k].x;
                sta[top].y=p[k].y;
                top++;
            }
            else
            {
				if(sta[top-1].y!=p[k].x)	
						return -1;
				res+=sta[top-1].x*p[k].x*p[k].y;
				sta[top-1].y=p[k].y;
				sta[top-1].c='*';
            }
        }
    }
    return res;
}
int main()
{
    int n,i;
    scanf("%d",&n);

    for(i=0;i<n;++i)
    {
        scanf("%s",s);
        p[s[0]-'A'].input();
		p[s[0]-'A'].c=s[0];
    }
    while(scanf("%s",m)!=EOF)
    {
        i=solve();
        if(i==-1)
            printf("error\n");
        else
            printf("%d\n",i);
    }
    return 0;
}


你可能感兴趣的:(c,input,Matrix,output)