UVA 442 - Matrix Chain Multiplication

本文介绍了一种解决矩阵链乘问题的有效算法,并通过使用栈来实现。该算法每次遇到字母将其加入栈中,遇到右括号则从栈顶取出两个元素进行计算,再将结果压回栈中。通过这种方式可以有效地计算出矩阵链乘所需的最小运算次数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接:https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=383

题目大意:矩阵链乘,学过线性代数应该都知道。

分析:利用栈,每次遇到字母就加入到栈中,每次遇到)就把栈顶开始的两个元素拿出来计算,然后再加入到栈中,因为输入的括号肯定是匹配的,所以根本就不用考虑(,遇到直接跳过就好了。

ac代码

#include<cstdio>
#include<stack>
#include<cstring>

using namespace std;

struct Matr
{
    int a;
    int b;
}matr[30];

int main()
{
    int n;
    scanf("%d", &n);
    getchar();
    for(int i = 1; i <= n; i++)
    {
        char c;
        scanf("%c", &c);
        int k = c - 'A';
        scanf("%d %d", &matr[k].a, &matr[k].b);
        getchar();
    }
    char str[100];
    while(scanf("%s", str) != EOF)
    {
        stack<Matr> s;
        int len = strlen(str);
        int sum = 0;
        int flag = 1;
        for(int i = 0; i < len; i++)
        {
            if(str[i] >= 'A' && str[i] <= 'Z')s.push(matr[str[i] - 'A']);
            else if(str[i] == ')')
            {
                Matr x, y, z;
                y = s.top();
                s.pop();
                x = s.top();
                s.pop();
                //printf("%d %d %d %d\n", x.a, x.b, y.a, y.b);
                if(x.b != y.a)
                {
                    flag = 0;
                    break;
                }
                else
                {
                    sum = sum + x.a * x.b * y.b;
                    z.a = x.a;
                    z.b = y.b;
                    s.push(z);
                    //printf("aaaaaaaaaaaaaa\n");
                }
            }
        }
        if(flag)printf("%d\n", sum);
        else printf("error\n");
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值