Given an array of N integers where N is an even number. There are two kinds of operations allowed on the array.
The task is to find the minimum number of operations required to remove all the element of the array.
If array is {10, 13} then minimum 2 operations are required
1. To remove numbers, we must transform two numbers to two consecutive primes. 2. Let us suppose a and b are the consecutive prime numbers then we use sieve of Eratosthenes to precompute prime numbers and then find the first prime p not greater than a and the first greater than p using array 3. Once this computation is done use dynamic programming to solve the problem
#include <iostream> #include <algorithm> #include <queue> using namespace std; int minimumPrefixReversals(int *a, int n) { string start = ""; string destination = "", t, r; for (int i = 0; i < n; i++) { start += to_string(a[i]); } sort(a, a + n); for (int i = 0; i < n; i++) { destination += to_string(a[i]); } queue<pair<string, int> > qu; pair<string, int> p; qu.push(make_pair(start, 0)); if (start == destination) { return 0; } while (!qu.empty()) { p = qu.front(); t = p.first; qu.pop(); for (int j = 2; j <= n; j++) { r = t; reverse(r.begin(), r.begin() + j); if (r == destination) { return p.second + 1; } qu.push(make_pair(r, p.second + 1)); } } } int main() { int a[] = { 1, 2, 4, 3 }; int n = sizeof(a) / sizeof(a[0]); cout << "Minimum reversal: " << minimumPrefixReversals(a, n) << endl; return 0; }
When you compile and execute above program. It generates following output:
Minimum reversal: 3