설명
주어진 N 배열 여기서 N은 짝수입니다. 어레이에는 두 가지 종류의 작업이 허용됩니다.
- 배열 요소의 값을 1만큼 증가시킵니다.
- 배열에서 인접한 두 요소가 연속적인 소수인 경우 두 요소를 모두 삭제합니다.
작업은 배열의 모든 요소를 제거하는 데 필요한 최소 작업 수를 찾는 것입니다.
예시
배열이 {10, 13}이면 최소 2개의 작업이 필요합니다.
- 증분 1 st 배열의 요소는 1만큼. 따라서 새 배열은 {11, 13} 이 됩니다.
- 1 st 삭제 그리고 2 nd 둘 다 연속적인 소수이므로 요소
알고리즘
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