forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
The Score of Students Solving Math Expression.cpp
114 lines (108 loc) · 3.08 KB
/
The Score of Students Solving Math Expression.cpp
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
class Solution {
int eval(int a, int b, char op) {
if (op == '+') {
return a + b;
} else {
return a * b;
}
}
unordered_map<string_view, unordered_set<int>> mp;
unordered_set<int> potential;
unordered_set<int>& solve(string_view s) {
if (auto it = mp.find(s); it != mp.end()) {
return it->second;
}
bool res = true;
int n = 0;
unordered_set<int> ans;
for (int i = 0; i < s.size(); i++) {
char c = s[i];
if (c >= '0' && c <= '9') {
n = n * 10 + (c - '0');
} else {
n = 0;
res = false;
for (int l : solve(s.substr(0, i))) {
for (int r : solve(s.substr(i + 1))) {
int res2 = eval(l, r, c);
if (res2 <= 1000) {
ans.insert(res2);
}
}
}
}
}
if (res) {
ans.insert(n);
}
return mp[s] = ans;
}
public:
int scoreOfStudents(string s, vector<int>& answers) {
int ans = 0, correct = 0;
stack<int> ns, op;
unordered_map<char, int> prec{
{'+', 1},
{'*', 2},
{'(', 0}
};
int n = 0;
for (int i = 0; i < s.size(); i++) {
char c = s[i];
if (c >= '0' && c <= '9') {
n = n * 10 + (c - '0');
} else if (c == '(') {
op.push(c);
} else if (c == ')') {
ns.push(n);
while (op.top() != '(') {
int b = ns.top();
ns.pop();
int a = ns.top();
ns.pop();
ns.push(eval(a, b, op.top()));
op.pop();
}
op.pop();
n = ns.top();
ns.pop();
} else {
ns.push(n);
n = 0;
int p = prec[c];
while (!op.empty() && prec[op.top()] >= p) {
int b = ns.top();
ns.pop();
int a = ns.top();
ns.pop();
ns.push(eval(a, b, op.top()));
op.pop();
}
op.push(c);
}
}
ns.push(n);
while (!op.empty()) {
int b = ns.top();
ns.pop();
int a = ns.top();
ns.pop();
ns.push(eval(a, b, op.top()));
op.pop();
}
correct = ns.top();
string_view sv{s.data(), s.size()};
solve(sv);
for (int n2 : mp[sv]) {
potential.insert(n2);
}
for (int n2 : answers) {
if (n2 == correct) {
ans += 5;
} else if (potential.find(n2) != potential.end()) {
ans += 2;
}
}
return ans;
}
};