UVA 442 Matrix Chain Multiplication

题意: 给出一些矩阵,和一些矩阵相乘的带括号表达式,问表达式是否符合矩阵乘法,以及它的计算次数。

解法: 用模拟栈水过去了。遇到‘(’就把当前矩阵入栈,遇到')'就出栈并乘以现在的矩阵,遇到矩阵就乘,跑完了打印答案。

笔者吐槽:计算顺序都给出来了,表示完全没有明白这一题的DP性质体现在哪里,为何它也在UVA的DP分类里- -!

/* **********************************************
Author      : Nero
Created Time: 2013-8-27 15:03:06
Problem id  : UVA 442
Problem Name: Matrix Chain Multiplication
*********************************************** */

#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <algorithm>
using namespace std;
#define REP(i,a,b) for(int i=(a); i<(int)(b); i++)
#define clr(a,b) memset(a,b,sizeof(a))
typedef long long lld;

lld sum;
struct Mat {
    int x,y;
    Mat operator * (Mat tt) {
        sum += (lld)x * y * tt.y;
        Mat ret = {x,tt.y};
        if(x == 0) ret.x = tt.x;
        return ret;
    }
}a[101000];
Mat hh[30];
char s[1010000];

bool judge() {
    int i;
    for(i = 0; s[i] ; i ++) if(isalpha(s[i])) break;
    int x = hh[s[i]-'A'].x;
    int y = hh[s[i]-'A'].y;
    if(s[i] == 0) return 1;
    for( i ++ ; s[i]; i ++) if(isalpha(s[i])) {
        if(y != hh[s[i] - 'A'].x) return 0;
        y = hh[s[i] - 'A'].y;
    }
    return 1;
}

int p;
void Solve() {
    int now = 0;
    a[0].x = a[0].y = 0;
    for(int i = 0; s[i]; i ++) {
        if(s[i] == '(') {
            now ++;
            a[now].x = a[now].y = 0;
        }
        else if(s[i] == ')') {
            now --;
            a[now] = a[now] * a[now+1];
        }
        else {
            int tt = s[i] - 'A';
            a[now] = a[now] * hh[tt];
        }
    }
}

int main() {
    int n ;
    scanf("%d", &n);
    while(n--) {
        scanf("%s", s);
        scanf("%d%d", &hh[s[0]-'A'].x, &hh[s[0]-'A'].y);
    }
    while(~scanf("%s", s)) {
        if(!judge()) printf("error\n");
        else {
            sum = 0;
            Solve();
            printf("%lld\n", sum);
        }
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值