首页 > 代码库 > nyoj1272表达式求值(递归法)
nyoj1272表达式求值(递归法)
---恢复内容开始---
感冒时写的,简直不忍直视
#include<iostream>
#include<cstring>
using namespace std;
#define LL long long
char s[1010];
LL judp(int,int);
LL judnum(int,int);
LL judc(int,int);
int fin(int st,int ed);
LL all(LL);
LL num(int st,int ed)
{
LL sum=0;
for(int i=st;i<=ed;++i) sum=sum*10+s[i]-‘0‘;
return sum;
}
LL dfs(int st,int ed)
{
int i,j,pp=judp(st,ed),pnum=judnum(st,ed),pc=judc(st,ed);
if(pnum!=-1) return num(st,ed);
else if(pp!=-1) {LL t1=dfs(st,pp-1),t2=dfs(pp+1,ed);
return t1+t2;}
else if (pc!=-1){
LL t1=dfs(st,pc-1),t2=dfs(pc+1,ed);
return t1*t2;
}
else if(s[st]==‘(‘&&s[ed]==‘)‘) return dfs(st+1,ed-1);
else if(s[st]==‘S‘){
int mid=fin(st,ed);
LL t1=dfs(st+5,mid-1),t2=dfs(mid+1,ed-1);
return max(all(t1),all(t2));
}
}
LL all(LL a)
{
LL s=0;
while(a){
s+=a%10;
a/=10;}
return s;
}
LL judp(int a,int b)
{
int i,c=0;
for(i=a;i<=b;++i){
if(s[i]==‘(‘) ++c;
else if(s[i]==‘)‘) --c;
if(s[i]==‘+‘&&c==0) return i;
}
return -1;
}
LL judnum(int st,int ed)
{
int flag=1,i,sum=0;
for(i=st;i<=ed;++i)
{
if(!isdigit(s[i])) return -1;
else sum+=s[i]-‘0‘;
}
return sum;
}
LL judc(int st,int ed)
{
int i,j,c=0;
for(int i=st;i<=ed;++i){
if(s[i]==‘(‘) ++c;
if(s[i]==‘)‘) --c;
if(c==0&&s[i]==‘*‘) return i;}
return -1;
}
int fin(int a,int b)
{
int c=0;
for(int i=a;i<=b;++i){
if(s[i]==‘(‘) ++c;
if(s[i]==‘)‘) --c;
if(c==1&&s[i]==‘,‘) return i;
}
}
int main()
{
int t;
cin>>t;
while(t--) cin>>s,cout<<dfs(0,strlen(s)-1)<<endl;
return 0;
}
---恢复内容结束---
nyoj1272表达式求值(递归法)