-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
minimum-operations-to-convert-number.cpp
38 lines (36 loc) · 1.3 KB
/
minimum-operations-to-convert-number.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
// Time: O(n * m), m is max x
// Space: O(m)
class Solution {
public:
int minimumOperations(vector<int>& nums, int start, int goal) {
static const int MAX_X = 1000;
vector<int> new_nums;
for (const auto& y : nums) {
if (y && ((0 <= y && y <= MAX_X) || (0 <= (goal - y) && (goal - y) <= MAX_X) || (0 <= (goal + y) && (goal + y) <= MAX_X) || (0 <= (goal ^ y) && (goal ^ y) <= MAX_X))) {
new_nums.emplace_back(y);
}
}
nums = move(new_nums);
vector<pair<int, int>> q = {{start, 0}};
unordered_set<int> lookup = {start};
while (!empty(q)) {
vector<pair<int, int>> new_q;
for (const auto& [x, steps] : q) {
for (const auto& y : nums) {
for (const auto& nx : {x + y, x - y, x ^ y}) {
if (nx == goal) {
return steps + 1;
}
if (!(0 <= nx && nx <= MAX_X) || lookup.count(nx)) {
continue;
}
lookup.emplace(nx);
new_q.emplace_back(nx, steps + 1);
}
}
}
q = move(new_q);
}
return -1;
}
};