- Define the priority key and whether the smallest or largest item should lead.
- Push each candidate when it becomes eligible.
- Discard stale entries when necessary and process the best live candidate.
Code notes
- 60 lines of C++ from the credited upstream file 3377.cpp.
- The implementation visibly relies on sequence storage, hash lookup, work queue.
- 4 loop blocks detected.
Complexity
Count heap pushes and pops; each normally contributes a logarithmic factor in the heap size.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public:3 int minOperations(int n, int m) {4 constexpr int kMax = 10000;5 const vector<bool> isPrime = sieveEratosthenes(kMax);6 if (isPrime[n] || isPrime[m])7 return -1;8 return dijkstra(n, m, isPrime);9 }10 11 private:12 int dijkstra(int src, int dst, const vector<bool>& isPrime) {13 unordered_set<int> seen{src};14 using P = tuple<int, int>; 15 priority_queue<P, vector<P>, greater<>> minHeap;16 minHeap.emplace(src, src);17 18 while (!minHeap.empty()) {19 const auto [cost, curr] = minHeap.top();20 minHeap.pop();21 if (curr == dst)22 return cost;23 string s = to_string(curr);24 for (int i = 0; i < s.length(); ++i) {25 if (s[i] < '9') {26 ++s[i];27 const int next = stoi(s);28 if (!isPrime[next] && !seen.contains(next)) {29 minHeap.emplace(cost + next, next);30 seen.insert(next);31 }32 --s[i];33 }34 if (s[i] > '0' && !(i == 0 && s[i] == '1')) {35 --s[i];36 const int next = stoi(s);37 if (!isPrime[next] && !seen.contains(next)) {38 minHeap.emplace(cost + next, next);39 seen.insert(next);40 }41 ++s[i];42 }43 }44 }45 46 return -1;47 }48 49 vector<bool> sieveEratosthenes(int n) {50 vector<bool> isPrime(n, true);51 isPrime[0] = false;52 isPrime[1] = false;53 for (int i = 2; i * i < n; ++i)54 if (isPrime[i])55 for (int j = i * i; j < n; j += i)56 isPrime[j] = false;57 return isPrime;58 }59};60