C. Prime Swaps
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output
You have an array a[1], a[2], ..., a[n], containing distinct integers from 1 ton. 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 andj (1 ≤ i < j ≤ n;(j - i + 1) is a prime number);
· swap the elements on positionsi andj; 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 most5n operations.
Input
The first line contains integer n (1 ≤ n ≤ 105). The next line contains n distinct integersa[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.
Examples
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
题目大意:
给你一个长度为N的序列,保证序列中元素是从1-N的,目标串是一个严格递增的序列,将原串改成目标串只有一种操作:
交换两个元素,对应两个元素为:a【i】,a【j】,其中要求j-i+1为素数。
要求在5n次操作以内解决这个问题,输出任意可行解即可。
思路:
1、首先设定一个数组pos【i】,表示数字i现在的位子。显然,如果pos【i】!=i,那么我们希望将这个数字i放到位子i。那么我们考虑从第一个数这样处理,一直处理到第N个数。那么我们处理每一个数的时候,将这个数向前交换,直到将这个数交换到位子i为止。
2、那么考虑上述过程实现:
①选择元素从1-N记做i,考虑将这个数交换到第i个位子。
②然后我们找一个位子j,使得这个位子j尽可能的小同时保证pos【i】-j+1是一个素数,然后将数字i现在所在位子和位子j进行交换。
③重复过程②直到数字i换到了位子i为止。
④记录这个交换过程输出即可。
3、本题靠着直觉XJB搞过的,证明实属为难,如果菊菊们找到了证明也希望大家分享一波。
Ac代码:
#include<stdio.h>
#include<algorithm>
#include<string.h>
#include<math.h>
using namespace std;
int pos[100050];
int a[100050];
int ans[100050*6][2];
int Is_or[100050];//0表示素数
void init()
{
memset(Is_or,0,sizeof(Is_or));
Is_or[0]=1;
Is_or[1]=1;
int a,b;
for(int j=2;j<sqrt(100050);j++)
{
if(Is_or[j]==0)
for(int k=j+j;k<=100050;k+=j)
{
Is_or[k]=1;
}
}
}
int main()
{
int n;
init();
while(~scanf("%d",&n))
{
for(int i=1;i<=n;i++)
{
scanf("%d",&a[i]);
pos[a[i]]=i;
}
int cont=0;
for(int i=1;i<=n;i++)
{
if(a[i]==i)continue;
while(1)
{
for(int j=i;j<pos[i];j++)
{
if(Is_or[pos[i]-j+1]==0)
{
ans[cont][0]=j;
ans[cont++][1]=pos[i];
int num=a[j];
swap(a[pos[i]],a[j]);
swap(pos[num],pos[i]);
break;
}
}
if(a[i]==i)break;
}
}
printf("%d\n",cont);
for(int i=0;i<cont;i++)
{
printf("%d %d\n",ans[i][0],ans[i][1]);
}
}
}