tyvj/joyoi 1043 表达式计算4

这题怎么这么毒瘤...

一开始我想转后缀表达式来计算,后来发现有负数...弃疗。

递归求解又发现会有多余括号,我觉得不行...

实在是毒瘤啊!

 1 #include <cstdio>
 2 #include <iostream>
 3 #include <string>
 4 typedef long long LL;
 5 std::string s;
 6 
 7 bool isop(char c) {
 8     if(c == '+') return 1;
 9     if(c == '-') return 1;
10     if(c == '*') return 1;
11     if(c == '/') return 1;
12     if(c == '^') return 1;
13     return 0;
14 }
15 
16 LL pow(LL a, LL b) {
17     LL ans = 1;
18     for(int i = 1; i <= b; i++) {
19         ans *= a;
20     }
21     return ans;
22 }
23 
24 LL solve(int l, int r) {
25     int f = 0;
26     int pos1 = -1, pos2 = -1, pos3 = -1;
27     for(int i = l; i <= r; i++) {
28         if(isop(s[i]) && (!f)) {
29             if(s[i] == '+' || s[i] == '-') {
30                 pos1 = i;
31             }
32             else if(s[i] == '*' || s[i] == '/') {
33                 pos2 = i;
34             }
35             else {
36                 pos3 = i;
37             }
38         }
39         else if(s[i] == '(') f++;
40         else if(s[i] == ')') f--;
41     }
42 
43     if(f > 0) {
44         LL temp = solve(l + 1, r);
45         return temp;
46     }
47     
48     if(f < 0) {
49         LL temp = solve(l, r - 1);
50         return temp;
51     }
52 
53     if(pos1 > l) {
54         if(s[pos1] == '+') {
55             return solve(l, pos1 - 1) + solve(pos1 + 1, r);
56         }
57         else {
58             return solve(l, pos1 - 1) - solve(pos1 + 1, r);
59         }
60     }
61     else if(pos2 != -1) {
62         if(s[pos2] == '*') {
63             return solve(l, pos2 - 1) * solve(pos2 + 1, r);
64         }
65         else {
66             return solve(l, pos2 - 1) / solve(pos2 + 1, r);
67         }
68     }
69     else if(pos3 != -1) {
70         return pow(solve(l, pos3 - 1), solve(pos3 + 1, r));
71     }
72     else if(s[l] == '(' && s[r] == ')'){
73         return solve(l + 1, r - 1);
74     }
75     else {
76         LL ans = 0;
77         int f = 1;
78         while(s[l] == '(') l++;
79         if(s[l] == '-') {
80             f = -1;
81             l++;
82         }
83         for(int i = l; i <= r; i++) {
84             if(s[i] == ')') break;
85             ans = ans * 10 + s[i] - '0';
86         }
87         return ans * f;
88     }
89 }
90 
91 int main() {
92     std::cin >> s;
93     printf("%lld", solve(0, s.size() - 1));
94     return 0;
95 }
AC代码
posted @ 2018-05-28 13:48  garage  阅读(176)  评论(0编辑  收藏  举报