algorithm - C++ lambda function in priority_queue with capture by reference -


i solving algorithm problem - "find k-th ugly number", below problem statement , implementation.

write program find n-th ugly number. ugly numbers positive numbers prime factors include 2, 3, 5.  example, 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 sequence of first 10 ugly numbers.  vector<int> tmp(1,1); vector<int> primes({2,3,5}); vector<int> indices(3, 0); // lambda function pass in variables captured reference priority_queue<int, vector<int>, function<bool(const int&, const int&)>> pq([&](const int& a, const int& b){     return primes[a] * tmp[indices[a]] > primes[b] * tmp[indices[b]]; }); pq.push(0); pq.push(1); pq.push(2); while(tmp.size() <= 3) { // find first 3 ugly number     int primeindex = pq.top();     pq.pop();     int nextval = primes[primeindex] * tmp[indices[primeindex]];     pq.push(primeindex + 1);     indices[primeindex]++;      while(!pq.empty() && primes[pq.top()] & tmp[indices[pq.top()]]) {         primeindex = pq.top();         pq.pop();         pq.push(primeindex + 1);         indices[primeindex]++;     }     cout << nextval << endl;     tmp.push_back(nextval); } return 0; 

the usage of priority_queue optimization solution. priority_queue finds "next ugly" number in o(logn) time. priority_queue uses index of primes[] elements. uses lambda function comparator , captures outside variables by reference. tested code output first 3 ugly numbers (should 2, 3, 4), code gave me "2, 6, 0". think there wrong lambda function in priority_queue, not find out why. give me hint on resolving bug? thank much.

the immediate problem code accessing tmp vector out of bounds. use elements of indices indices tmp, , increment elements of indices in multiple places within iteration of outer while loop (once before inner while loop, , potentially 1 or more times within inner while loop), , increase size of tmp @ end of iteration of outer while loop. in meantime, in condition of inner while loop, index tmp indices may have increased (potentially multiple times) before increasing size of tmp.


Comments

Popular posts from this blog

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

python Tkinter Capturing keyboard events save as one single string -

sql server - Why does Linq-to-SQL add unnecessary COUNT()? -