hdu1082

这篇博客探讨了如何解决HDU1082题目,该问题涉及到矩阵链乘法的动态规划解决方案。文章强调了在求解过程中栈作为一种数据结构的重要应用。
摘要由CSDN通过智能技术生成

题目链接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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值