hdu1082

来源:互联网 发布:linux内核架构 编辑:程序博客网 时间:2024/06/15 09:21

题目链接Matrix Chain Multiplication


看题目以后是DP,其实是栈的使用

#include <iostream>#include <stdio.h>#include <stack>#include <string.h>using namespace std;const int maxn=1005;struct node{    char c;    int x,y;}matrix[26];int main(){    //freopen("in.txt","r",stdin);    int n;    char ch,str[maxn];    stack<node>st;    bool tag;    node a,b,c;    int x,y,ans;    scanf("%d",&n);    for(int i=0;i<n;i++){        getchar();        scanf("%c %d %d",&ch,&x,&y);        matrix[ch-'A'].c=ch;        matrix[ch-'A'].x=x;        matrix[ch-'A'].y=y;    }    c.c='(';    while(scanf("%s",str)!=EOF){        while(!st.empty())st.pop();        ans=0;        tag=true;        int len=strlen(str);        for(int i=0;i<len;i++){            if(str[i]==')'){                b=st.top();st.pop();                a=st.top();st.pop();                if((st.top()).c=='(')st.pop();                if(a.y!=b.x){                    tag=false;                    break;                }                else{                    ans+=a.x*a.y*b.y;                    a.y=b.y;                    st.push(a);                }            }            else if (str[i]=='('){                st.push(c);            }            else {                a=matrix[str[i]-'A'];                st.push(a);            }        }        //print        while(tag&&st.size()>1){            a=st.top();st.pop();            b=st.top();st.pop();            c.x=a.x;            c.y=b.y;            st.push(c);            ans+=a.x*a.y*b.y;        }        if(tag)printf("%d\n",ans);        else printf("error\n");    }    return 0;}


0 0
原创粉丝点击