标签:
3 12+2*3 12*(2+3) 12*(2+3)+Smax(333,220+280)
18 60 69
#include<iostream> #include<cstdio> #include<cstring> #include<cmath> #include<algorithm> #include<stack> using namespace std; char judge(char a, char b){ if(a == ‘#‘)return ‘<‘; if(a == ‘(‘ && b == ‘)‘) return ‘=‘; if(b == ‘)‘) return ‘>‘; if(a == ‘+‘){ if(b == ‘*‘ || b == ‘(‘) return ‘<‘; else return ‘>‘; } if(a == ‘*‘){ if(b == ‘(‘) return ‘<‘; else return ‘>‘; } if(a == ‘(‘)return ‘<‘; } bool Is_digit(char c){ if(c >= ‘0‘ && c <= ‘9‘) return true; return false; } int work(int a, char c, int b){ switch(c){ case ‘+‘: return a + b; case ‘*‘: return a * b; } } int Smax(char *s); int js(char *s){ stack<char>S; stack<int>s2; S.push(‘#‘); for(int i = 0; s[i];){ if(s[i] == ‘,‘){ while(S.size() > 1){ if(s2.size() == 1)return s2.top(); int a = s2.top(); s2.pop(); int b = s2.top(); s2.pop(); s2.push(work(a, S.top(), b)); S.pop(); } return s2.top(); } else if(s[i] == ‘S‘){ int px, cnt = 0, px1; for(int j = i; s[j]; j++){ if(s[j] == ‘(‘ && cnt == 0){ px1 = j; } if(s[j] == ‘(‘) cnt++; else if(s[j] == ‘)‘) cnt--; if(cnt == 0 && s[j] == ‘)‘){ px = j;break; } } s2.push(Smax(s + px1 + 1)); i = px + 1; } else if(Is_digit(s[i])){ int temp = 0; while(Is_digit(s[i])){ temp = temp * 10 + s[i] - ‘0‘; i++; } // printf("%d\n", temp); s2.push(temp); } else{ int a, b; // printf("%c %c\n", S.top(), s[i]); if(S.size() == 1 && s[i] == ‘)‘){ return s2.top(); } switch(judge(S.top(), s[i])){ case ‘<‘: S.push(s[i]); i++; break; case ‘>‘: a = s2.top(); s2.pop(); b = s2.top(); s2.pop(); s2.push(work(a, S.top(), b)); S.pop(); break; // printf("%d\n", work(a, S.top(), b)); case ‘=‘: S.pop(); i++; } } } while(S.size() > 1){ int a = s2.top(); s2.pop(); int b = s2.top(); s2.pop(); s2.push(work(a, S.top(), b)); S.pop(); } return s2.top(); } int Chenge(int x){ int temp = 0; while(x){ temp += x % 10; x /= 10; } return temp; } int Smax(char *s){ int px = 0, px2 = 0, cnt = 0; for(int i = 0; s[i]; i++){ if(s[i] == ‘(‘) cnt++; else if(s[i] == ‘)‘) cnt--; if(cnt == 0 && s[i] == ‘,‘) px = i; } return max(Chenge(js(s)), Chenge(js(s + px + 1))); } int main(){ int T; scanf("%d", &T); char s[1010]; while(T--){ scanf("%s", s); printf("%d\n", js(s)); } return 0; }
标签:
原文地址:http://www.cnblogs.com/handsomecui/p/5588920.html