题目链接:Call of Accepted
题解:dfs根据优先级先后计算。参考博客
#include<string.h> #include<bits/stdc++.h> #include<algorithm> #include<queue> #define ll long long using namespace std; #define INF 0xffffff #define MAXN 300010 const int N=1e2+50; char s[N]; bool v[N][N][2]; ll val[N][N][2]; int p[N]; stack<int>st; ll dfs(int l,int r,int f) { if(v[l][r][f])return val[l][r][f]; v[l][r][f]=1; int cnt=0; for(int i=r;i>=l;i--) { if(s[i]=='(')cnt--; if(s[i]==')')cnt++; if(s[i]=='+'&&!cnt) { if(f==0)return val[l][r][f]=dfs(l,i-1,0)+dfs(i+1,r,0); else return val[l][r][f]=dfs(l,i-1,1)+dfs(i+1,r,1); } else if(s[i]=='-'&&!cnt) { if(f==0)return val[l][r][f]=dfs(l,i-1,0)-dfs(i+1,r,1); else return val[l][r][f]=dfs(l,i-1,1)-dfs(i+1,r,0); } } cnt=0; for(int i=r;i>=l;i--) { if(s[i]=='(')cnt--; if(s[i]==')')cnt++; if(s[i]=='*'&&!cnt) { if(f==0) { val[l][r][f]=dfs(l,i-1,0)*dfs(i+1,r,0); val[l][r][f]=min(val[l][r][f],dfs(l,i-1,0)*dfs(i+1,r,1)); val[l][r][f]=min(val[l][r][f],dfs(l,i-1,1)*dfs(i+1,r,0)); return val[l][r][f]=min(val[l][r][f],dfs(l,i-1,1)*dfs(i+1,r,1)); } else { val[l][r][f]=dfs(l,i-1,0)*dfs(i+1,r,0); val[l][r][f]=max(val[l][r][f],dfs(l,i-1,0)*dfs(i+1,r,1)); val[l][r][f]=max(val[l][r][f],dfs(l,i-1,1)*dfs(i+1,r,0)); return val[l][r][f]=max(val[l][r][f],dfs(l,i-1,1)*dfs(i+1,r,1)); } } } cnt=0; for(int i=r;i>=l;i--) { if(s[i]=='(')cnt--; if(s[i]==')')cnt++; if(s[i]=='d'&&!cnt) { if(f==0)return val[l][r][f]=dfs(l,i-1,0); else return val[l][r][f]=dfs(l,i-1,1)*dfs(i+1,r,1); } } if(s[l]=='('&&p[l]==r)return val[l][r][f]=dfs(l+1,p[l]-1,f); ll sum=0; for(int i=l;i<=r;i++) { sum=sum*10+s[i]-'0'; } //cout<<"$$$"<<sum<<endl; return val[l][r][f]=sum; } int main() { while(scanf("%s",s+1)!=EOF) { memset(v,0,sizeof(v)); int len=strlen(s+1); for(int i=1;i<=len;i++) { if(s[i]=='(')st.push(i); if(s[i]==')') { int tmp=st.top(); st.pop(); p[tmp]=i; } } //cout<<dfs(1,len,0)<<endl; printf("%lld %lld ",dfs(1,len,0),dfs(1,len,1)); } return 0; }