题意: 给出一些矩阵,和一些矩阵相乘的带括号表达式,问表达式是否符合矩阵乘法,以及它的计算次数。
解法: 用模拟栈水过去了。遇到‘(’就把当前矩阵入栈,遇到')'就出栈并乘以现在的矩阵,遇到矩阵就乘,跑完了打印答案。
笔者吐槽:计算顺序都给出来了,表示完全没有明白这一题的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;
}