codeforces 432c 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 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;
}


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值