|
| 1 | +// Time: O(n^3 * a^2) |
| 2 | +// Space: O(n^2) |
| 3 | + |
| 4 | +class Solution { |
| 5 | +public: |
| 6 | + int scoreOfStudents(string s, vector<int>& answers) { |
| 7 | + static const int MAX_ANS = 1000; |
| 8 | + |
| 9 | + const int n = (size(s) + 1) / 2; |
| 10 | + vector<vector<unordered_set<int>>> dp(n, vector<unordered_set<int>>(n)); |
| 11 | + for (int i = 0; i < n; ++i) { |
| 12 | + dp[i][i].emplace(s[i * 2] - '0'); |
| 13 | + } |
| 14 | + for (int l = 1; l < n; ++l) { |
| 15 | + for (int left = 0; left < n - l; ++left) { |
| 16 | + const int right = left + l; |
| 17 | + for (int k = left; k < right; ++k) { |
| 18 | + for (const auto& x : dp[left][k]) { |
| 19 | + for (const auto& y : dp[k + 1][right]) { |
| 20 | + const int z = (s[2 * k + 1] == '+') ? x + y : x * y; |
| 21 | + if (z <= MAX_ANS) { |
| 22 | + dp[left][right].emplace(z); |
| 23 | + } |
| 24 | + } |
| 25 | + } |
| 26 | + } |
| 27 | + } |
| 28 | + } |
| 29 | + const int target = evaluate(s); |
| 30 | + int result = 0; |
| 31 | + for (const auto& ans : answers) { |
| 32 | + if (ans == target) { |
| 33 | + result += 5; |
| 34 | + } else if (dp.front().back().count(ans)) { |
| 35 | + result += 2; |
| 36 | + } |
| 37 | + } |
| 38 | + return result; |
| 39 | + } |
| 40 | + |
| 41 | +private: |
| 42 | + int evaluate(const string& s) { |
| 43 | + static const unordered_map<char, int> precedence = {{'+', 0}, {'*', 1}}; |
| 44 | + |
| 45 | + vector<int64_t> operands; |
| 46 | + vector<char> operators; |
| 47 | + int64_t operand = 0; |
| 48 | + for (const auto& c : s) { |
| 49 | + if (isdigit(c)) { |
| 50 | + operands.emplace_back(c - '0'); |
| 51 | + } else { |
| 52 | + while (!empty(operators) && precedence.at(operators.back()) >= precedence.at(c)) { |
| 53 | + compute(&operands, &operators); |
| 54 | + } |
| 55 | + operators.emplace_back(c); |
| 56 | + } |
| 57 | + } |
| 58 | + while (!empty(operators)) { |
| 59 | + compute(&operands, &operators); |
| 60 | + } |
| 61 | + return operands.back(); |
| 62 | + } |
| 63 | + |
| 64 | + template<typename T> |
| 65 | + void compute(vector<T> *operands, vector<char> *operators) { |
| 66 | + const auto right = operands->back(); operands->pop_back(); |
| 67 | + const auto left = operands->back(); operands->pop_back(); |
| 68 | + const char op = operators->back(); operators->pop_back(); |
| 69 | + if (op == '+') { |
| 70 | + operands->emplace_back(left + right); |
| 71 | + } else if (op == '*') { |
| 72 | + operands->emplace_back(left * right); |
| 73 | + } |
| 74 | + } |
| 75 | +}; |
0 commit comments