You have an array a[1], a[2], ..., a[n], containing distinct integers from 1 to n. Your task is to sort this array in increasing order with the following operation (you may need to apply it multiple times):
- choose two indexes, i and j (1 ≤ i < j ≤ n; (j - i + 1) is a prime number);
- swap the elements on positions i and j; in other words, you are allowed to apply the following sequence of assignments:tmp = a[i], a[i] = a[j], a[j] = tmp (tmp is a temporary variable).
You do not need to minimize the number of used operations. However, you need to make sure that there are at most 5n operations.
The first line contains integer n (1 ≤ n ≤ 105). The next line contains n distinct integers a[1], a[2], ..., a[n] (1 ≤ a[i] ≤ n).
In the first line, print integer k (0 ≤ k ≤ 5n) — the number of used operations. Next, print the operations. Each operation must be printed as "i j" (1 ≤ i < j ≤ n; (j - i + 1) is a prime).
If there are multiple answers, you can print any of them.
3 3 2 1
1 1 3
2 1 2
0
4 4 2 3 1
3 2 4 1 2 2 4
题目链接: 点击打开链接
给出n长度的序列, 要求给序列排序, j - i + 1为素数时可以交换a[i], a[j], 要求输出交换的过程, 次数不得超过5 * n.
由于序列是1 - n, 所以我们进行n次排序, 类似选择排序, 每次使该位置的数归位, 从当前位置到pos[i], 找到是素数的点交换, 保存即可.
AC代码:
#include "iostream"
#include "cstdio"
#include "cstring"
#include "algorithm"
#include "queue"
#include "stack"
#include "cmath"
#include "utility"
#include "map"
#include "set"
#include "vector"
#include "list"
#include "string"
#include "cstdlib"
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> pii;
#define st first
#define nd second
#define exp 1e-8
#define lson l, m, rt << 1
#define rson m + 1, r, rt << 1 | 1
const int MOD = 1e9 + 7;
const int INF = 0x3f3f3f3f;
const double PI = acos(-1.0);
const int MAXN = 1e5 + 5;
int n, a[MAXN], prime[MAXN], pos[MAXN];
std::vector<pii > v;
int main(int argc, char const *argv[])
{
for(int i = 2; i < MAXN; ++i)
if(prime[i] == 0)
for(int j = 2 * i; j < MAXN; j += i)
prime[j] = 1;
scanf("%d", &n);
for(int i = 1; i <= n; ++i) {
scanf("%d", &a[i]);
pos[a[i]] = i;
}
for(int i = 1; i <= n; ++i)
for(int j = pos[i]; j > i; ) {
int x = i;
while(prime[j - x + 1]) x++;
pos[a[x]] = j, pos[a[j]] = x;
v.push_back(make_pair(x, j));
swap(a[x], a[j]);
j = x;
}
printf("%d\n", v.size());
for(int i = 0; i < v.size(); ++i)
printf("%d %d\n", v[i].st, v[i].nd);
return 0;
}