首页 > 代码库 > uva442
uva442
这题说的是给了一个矩阵连乘的表达式,要求判断是否合法,括符是合法的就是表达式可能不合法 , 不合法的 输出 error 合法的输出 多少次运算, 采用递归 找到对应的区间递归下去
#include <iostream>#include <cstdio>#include <algorithm>#include <string.h>using namespace std;typedef long long ll;typedef pair<ll,ll> P;char str[1000005];P R[30];ll ans;int idx(char A){ return A-‘A‘; }void dfs(int Lc, int Rc, P &E){ if(ans==-1) return ; E.first=E.second=-1; if(Lc>=Rc){ if(Lc==Rc&&str[Lc]!=‘(‘&&str[Lc]!=‘)‘){ E=R[idx(str[Lc])]; } return ; } P F; bool f=false; for(int i=Lc; i<=Rc; ++i){ if(str[i]==‘(‘){ P W; int num=1,j=i; while(num!=0){ j++; if(str[j]==‘(‘) num++; else if(str[j]==‘)‘) num--; } dfs(i+1,j-1,W); if(ans==-1) return ; i = j ; if(f==false){ f=true; F=W; }else{ if( F.second != W.first ){ ans=-1; return ; } ans+= F.first*F.second*W.second; F.second=W.second; } }else{ int loc=str[i]-‘A‘; if(f==false){ f=true; F=R[loc]; }else{ if(F.second!=R[loc].first){ ans=-1; return ; } ans+= F.first*F.second*R[loc].second; F.second=R[loc].second; } } } E=F;}int main(){ int n; char st[5]; scanf("%d",&n); for(int i=0; i<n; ++i){ scanf("%s",st); scanf("%lld%lld",&R[st[0]-‘A‘].first,&R[st[0]-‘A‘].second); } while(scanf("%s",str)==1){ int len= strlen(str); ans=0; P f; dfs(0,len-1,f); if(ans==-1){ printf("error\n"); } else printf("%lld\n",ans); } return 0;}
uva442
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。