POJ 2246 Matrix Chain Multiplication

用栈来处理一下就好了。

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<map>
using namespace std;

struct Mar
{
    int r,c;
} mar[3000000];
int n;
char s[100000];
int r,c,top,flag;
Mar Stack[1000000];

int main()
{
    scanf("%d",&n);
    for(int i=0; i<n; i++)
    {
        scanf("%s%d%d",s,&r,&c);
        mar[s[0]-'A'].r=r;
        mar[s[0]-'A'].c=c;
    }
    while(~scanf("%s",s))
    {
        int len=strlen(s);
        flag=0;
        top=-1;
        for(int i=0; i<len; i++)
        {
            if(top==-1)
            {
                top++;
                if(s[i]>='A'&&s[i]<='Z')
                    Stack[top]=mar[s[i]-'A'];
                else
                {
                    Mar node;
                    node.c=-1;
                    node.r=-1;
                    Stack[top]=node;
                }
                continue;
            }
            if(s[i]=='(')
            {
                Mar node;
                node.c=-1;
                node.r=-1;
                top++;
                Stack[top]=node;
            }
            else if(s[i]==')')
            {
                top--;
                Stack[top]=Stack[top+1];
                if(top-1!=-1&&Stack[top-1].c!=-1&&Stack[top-1].r!=-1)
                {
                    if(Stack[top-1].c!=Stack[top].r)
                    {
                        flag=-1;
                        break;
                    }
                    else
                    {
                        flag=flag+Stack[top-1].c*Stack[top-1].r*Stack[top].c;
                        Stack[top-1].c=Stack[top].c;
                        top--;
                    }
                }
            }
            else
            {
                Mar node;
                node.c=mar[s[i]-'A'].c;
                node.r=mar[s[i]-'A'].r;
                top++;
                Stack[top]=node;
                if(Stack[top-1].r!=-1&&Stack[top-1].c!=-1)
                {
                    if(Stack[top-1].c!=Stack[top].r)
                    {
                        flag=-1;
                        break;
                    }
                    else
                    {
                        flag=flag+Stack[top-1].c*Stack[top-1].r*Stack[top].c;
                        Stack[top-1].c=Stack[top].c;
                        top--;
                    }
                }
            }
        }
        if(flag==-1) printf("error\n");
        else printf("%d\n",flag);
    }
    return 0;
}

 

posted @ 2015-08-08 21:30  Fighting_Heart  阅读(193)  评论(0编辑  收藏  举报