UVa 442 - Matrix Chain Multiplication

本文介绍了一个使用栈进行操作的程序,该程序通过读取输入来处理矩阵运算表达式,特别是矩阵乘法运算。它实现了矩阵的压栈和弹栈操作,并验证了矩阵乘法运算的有效性。文章提供了一个具体的实现示例,包括如何处理输入、如何定义和使用栈等关键步骤。

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

/*
栈操作
*/
#include <cstdio>
#include <cstring>
#include <cctype>
#include <algorithm>
using namespace std;
const int MAXN = 26;
const int BUFF_SIZE = 1024;
int r[MAXN], c[MAXN];
int n;
char buff[BUFF_SIZE];
int str[BUFF_SIZE], stc[BUFF_SIZE], fr;

void push(int a, int b)
{
    str[fr] = a;
    stc[fr++] = b;
}

void pop(int &a, int &b)
{
    fr--;
    a = str[fr];
    b = stc[fr];
}

int main() {
    #ifndef ONLINE_JUDGE
    freopen("in.txt", "r", stdin);
    #endif
    scanf("%d\n", &n);
    int j;
    for(int i=0; i<n; i++) {
        j = getchar() - 'A';
        scanf("%d%d\n", &r[j], &c[j]);
    }
    while(gets(buff)) {
        if(buff[0] != '(') {
            printf("0\n"); continue;
        }
        int sum = 0;
        char *p = buff;
        fr = 0;
        while(*p) {
            if(*p == ')') {
                int r1, c1, r2, c2;
                pop(r1, c1);
                pop(r2, c2);
                if(c2 != r1) {
                    sum = -1;  break;
                }
                sum += r2 * c2 * c1;
                push(r2, c1);
            } else if(*p != '('){
                int i = *p - 'A';
                push(r[i], c[i]);
            }
            p++;
        }
        if(sum < 0) printf("error\n");
        else printf("%d\n", sum);
    }
    return 0;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值