1class Solution {2int eval(int a, int b, char op) {3if (op == '+') {4return a + b;5} else {6return a * b;7}8}910unordered_map<string_view, unordered_set<int>> mp;11unordered_set<int> potential;1213unordered_set<int> &solve(string_view s) {14if (auto it = mp.find(s); it != mp.end()) {15return it->second;16}1718bool res = true;19int n = 0;20unordered_set<int> ans;21for (int i = 0; i < s.size(); i++) {22char c = s[i];23if (c >= '0' && c <= '9') {24n = n * 10 + (c - '0');25} else {26n = 0;27res = false;28for (int l : solve(s.substr(0, i))) {29for (int r : solve(s.substr(i + 1))) {30int res2 = eval(l, r, c);31if (res2 <= 1000) {32ans.insert(res2);33}34}35}36}37}38if (res) {39ans.insert(n);40}41return mp[s] = ans;42}4344public:45int scoreOfStudents(string s, vector<int> &answers) {46int ans = 0, correct = 0;47stack<int> ns, op;48unordered_map<char, int> prec{{'+', 1}, {'*', 2}, {'(', 0}};49int n = 0;50for (int i = 0; i < s.size(); i++) {51char c = s[i];52if (c >= '0' && c <= '9') {53n = n * 10 + (c - '0');54} else if (c == '(') {55op.push(c);56} else if (c == ')') {57ns.push(n);58while (op.top() != '(') {59int b = ns.top();60ns.pop();61int a = ns.top();62ns.pop();63ns.push(eval(a, b, op.top()));64op.pop();65}66op.pop();67n = ns.top();68ns.pop();69} else {70ns.push(n);71n = 0;72int p = prec[c];73while (!op.empty() && prec[op.top()] >= p) {74int b = ns.top();75ns.pop();76int a = ns.top();77ns.pop();78ns.push(eval(a, b, op.top()));79op.pop();80}81op.push(c);82}83}84ns.push(n);85while (!op.empty()) {86int b = ns.top();87ns.pop();88int a = ns.top();89ns.pop();90ns.push(eval(a, b, op.top()));91op.pop();92}93correct = ns.top();9495string_view sv{s.data(), s.size()};96solve(sv);97for (int n2 : mp[sv]) {98potential.insert(n2);99}100101for (int n2 : answers) {102if (n2 == correct) {103ans += 5;104} else if (potential.find(n2) != potential.end()) {105ans += 2;106}107}108return ans;109}110};