time limit per test
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.
Input
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).
Output
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.
Sample test(s)
Input
3
3 2 1
Output
1
1 3
Input
2
1 2
Output
0
Input
4
4 2 3 1
Output
3
2 4
1 2
2 4
题解:
因为每个位置i上的数值都为i,而且每个数都有“分解质因数”,所以自然也可以拆成质数的和。
我们要做到,就是用尽量少(并非是为了求最小,只是为了尽量不超过5n)的步数,将数字i从当前位置换到i位置上。
#include<cstdio>
#include<cstring>
#include<iostream>
#include<cstdlib>
#include<cmath>
using namespace std;
int n,a[100002],zz=0;
bool p[100002];
struct daan
{int x,y;} ans[500002];
void change(int x,int y)
{
if(x==y) return;
if(x>y) swap(x,y);
for(int i=y;i>x;i--)
{if(p[i-x+1])
{swap(a[x],a[i]);
ans[++zz].x=x; ans[zz].y=i;
change(i,y); break;
}
}
}
void sushu()
{
memset(p,true,sizeof(p));
p[0]=p[1]=false;
for(int i=2;i<=100000;i++)
{if(p[i])
{for(int j=2*i;j<=100000;j=j+i)
p[j]=false;
}
}
}
int main()
{
sushu();
scanf("%d",&n);
for(int i=1;i<=n;i++)
scanf("%d",&a[i]);
for(int i=1;i<=n;i++)
{while(i!=a[i]) change(i,a[i]);}
printf("%d\n",zz);
for(int i=1;i<=zz;i++)
printf("%d %d\n",ans[i].x,ans[i].y);
return 0;
}