H Step Debugging
思路:把repeat看作(,library看作1,arithmetic忽略,for看作 ) ,乘上的是数字字符串,读到fin结束,在加上亿些小细节大致可以把原串处理成一个带有+- ()运算符的数字表达式,然后计算的表达式结果就是答案,计算模板可以参考*基本计算器III(力扣的付费题),赛后代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
| #include<bits/stdc++.h> #define int long long using namespace std; const int mod=20220911; int calculate(string s) { int n = s.size(), num = 0, curRes = 0, res = 0; char op = '+'; for (int i = 0; i < n; ++i) { char c = s[i]; if (c >= '0' && c <= '9') { num = num * 10 + c - '0'; } else if (c == '(') { int j = i, cnt = 0; for (; i < n; ++i) { if (s[i] == '(') ++cnt; if (s[i] == ')') --cnt; if (cnt == 0) break; } num = calculate(s.substr(j + 1, i - j - 1)); } if (c == '+' || c == '-' || c == '*' || c == '/' || i == n - 1) { switch (op) { case '+': curRes =(curRes%mod + num%mod)%mod; break; case '-': curRes =(curRes%mod - num%mod+mod)%mod; break; case '*': curRes =(curRes%mod*num%mod)%mod; break; case '/': curRes /= num; break; } if (c == '+' || c == '-' || i == n - 1) { res = (res%mod+curRes%mod)%mod; curRes = 0; } op = c; num = 0; } } return res%mod; } signed main(){ string s,t; int cheng=0; while(cin>>s&&s!="fin"){ if(s=="repeat"&&cheng==0){ if(t.size()>=1&&t[t.size()-1]>='0'&&t[t.size()-1]<='9') t+='+'; cheng=1; t+='('; }else if(s=="repeat"&&cheng==1){ if(t.size()>=1&&t[t.size()-1]>='0'&&t[t.size()-1]<='9') t+='+'; else if(t.size()>=1&&t[t.size()-1]!='(') t+='*'; t+='('; }else if(s=="library"){ if(t.size()>=1&&t[t.size()-1]!='(') t+='+'; t+='1'; }else if(s[0]>='1'&&s[0]<='9'){ t+='*'; t+=s; }else if(s=="for"){ t+=')'; } } cout<<calculate(t)<<endl; return 0; }
|