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
题意:给你一个序列,每次只能交换距离为素数-1的两个位置的值,让你输出一个在5*n步内将序列升序的方案。
分析:根据哥德巴赫猜想,我们可以在3*n内构造出一个解。
#include <cstdio>
#include <iostream>
#include <algorithm>
using namespace std;
int n,tot,num,f[100001],prim[200001],now[100001],ans[500005][2];
bool jud[200001];
void Swap(int x,int y)
{
tot++;
ans[tot][0] = x,ans[tot][1] = y;
swap(now[x],now[y]);
f[now[x]] = x;
f[now[y]] = y;
}
void got(int x,int y)
{
if(y == x + 1)
{
Swap(x,y);
return;
}
if(((y - x + 1) & 1) != 1)
{
got(x,y-1);
Swap(y-1,y);
}
else
{
for(int i = 1;i <= num;i++)
if(!jud[y - x + 2 - prim[i]])
{
Swap(x,x+prim[i]-1);
Swap(x+prim[i]-1,y);
break;
}
}
}
int main()
{
for(int i = 2;i <= 200000;i++)
{
if(!jud[i])
{
prim[++num] = i;
for(int j = 2*i;j <= 200000;j += i) jud[j] = true;
}
}
cin.sync_with_stdio(false);
cin>>n;
for(int i = 1;i <= n;i++)
{
cin>>now[i];
f[now[i]] = i;
}
for(int i = n;i;i--)
{
if(f[i] == i) continue;
got(f[i],i);
}
cout<<tot<<endl;
for(int i = 1;i <= tot;i++) cout<<ans[i][0]<<" "<<ans[i][1]<<endl;
}