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
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP