Codeforces Round #246 (Div. 2) C. Prime Swaps

43 篇文章 0 订阅
34 篇文章 0 订阅

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.

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


题意:给你一个序列,每次只能交换距离为素数-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;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值