在C ++中删除数组所需的最少操作
本文向大家介绍在C ++中删除数组所需的最少操作,包括了在C ++中删除数组所需的最少操作的使用技巧和注意事项,需要的朋友参考一下
描述
给定N个整数数组,其中N是偶数。数组上允许两种操作。
将数组的任何元素的值增加1。
如果数组中的两个相邻元素是连续的素数,请删除两个元素。
任务是找到删除数组中所有元素所需的最少操作数。
示例
如果数组为{10,13},则至少需要2次操作
将数组的第1元素递增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