C++ 中移除陣列所需的最小運算元
描述
給定一個包含 **N** 個整數的陣列,其中 N 是偶數。陣列上允許兩種操作。
- 將陣列中任何元素的值增加 1。
- 如果陣列中兩個相鄰元素是連續的素數,則刪除這兩個元素。
任務是找到移除陣列中所有元素所需的最小運算元。
示例
如果陣列是 {10, 13},則需要 2 個最小運算元
- 將陣列的第一個元素加 1。因此新陣列變為 {11, 13}
- 刪除第一個和第二個元素,因為它們都是連續的素數
演算法
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; }
編譯並執行上述程式時,會生成以下輸出
輸出
Minimum reversal: 3
廣告