ZJU-1094

 

典型DP问题矩阵连乘顺序的逆问题。
给出矩阵尺寸和连乘的表达式,求用乘法的次数。

从前往后不停的二合一,括号内可以视为一个矩阵,递归求解。
这道题的AC率好高,可能也有测试数据的功劳
//2008-01-12 16:35:10 Accepted 1094 C++ 00:00.00 432K #include<stdio.h> #include<string.h> struct matrix { int a,b; }; char exp[100]; int pe;//处理表达式的当前指针 int len;//表达式长度 int mt;//已乘次数 bool iserr;//错误标志,1表示有错,0表示没错 matrix inmat[27]; matrix getsub() { matrix ta,tb; if(exp[pe]=='(') { pe++; ta = getsub(); } else { ta = inmat[exp[pe]-65]; pe++; } while(pe<len && exp[pe]!=')') { if(exp[pe]=='(') { pe++; tb = getsub(); } else { tb = inmat[exp[pe]-65]; pe++; } if(ta.b==tb.a) { mt += ta.a*ta.b*tb.b; ta.b = tb.b; } else { iserr=true; return ta; } } if(exp[pe]==')') pe++; return ta; } int solve(char exp[100]) { len = strlen(exp); if(len==1) return 0; else { pe=0; mt=0; iserr=false; getsub(); if(iserr) return -1; else return mt; } } int main() { freopen("1094.txt","r",stdin); int n,k,t; char str; scanf("%d",&n); for(k=0;k<n;k++) { scanf("/n%c",&str); scanf(" %d %d",&inmat[str-65].a,&inmat[str-65].b); } //第一部分输入结束 while(scanf("%s",exp)!=EOF) { t = solve(exp); if(t>=0) printf("%d/n",t); else printf("error/n"); } fclose(stdin); return 0; }  

 

你可能感兴趣的:(ZJU-1094)