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

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 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


题目链接: 点击打开链接

给出n长度的序列, 要求给序列排序, j - i + 1为素数时可以交换a[i], a[j], 要求输出交换的过程, 次数不得超过5 * n.

由于序列是1 - n, 所以我们进行n次排序, 类似选择排序, 每次使该位置的数归位, 从当前位置到pos[i], 找到是素数的点交换, 保存即可.

AC代码:

#include "iostream"
#include "cstdio"
#include "cstring"
#include "algorithm"
#include "queue"
#include "stack"
#include "cmath"
#include "utility"
#include "map"
#include "set"
#include "vector"
#include "list"
#include "string"
#include "cstdlib"
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> pii;
#define st first
#define nd second
#define exp 1e-8
#define lson l, m, rt << 1
#define rson m + 1, r, rt << 1 | 1
const int MOD = 1e9 + 7;
const int INF = 0x3f3f3f3f;
const double PI = acos(-1.0);
const int MAXN = 1e5 + 5;
int n, a[MAXN], prime[MAXN], pos[MAXN];
std::vector<pii > v;
int main(int argc, char const *argv[])
{
	for(int i = 2; i < MAXN; ++i)
		if(prime[i] == 0) 
			for(int j = 2 * i; j < MAXN; j += i) 
				prime[j] = 1;
	scanf("%d", &n);
	for(int i = 1; i <= n; ++i) {
		scanf("%d", &a[i]);
		pos[a[i]] = i;
	}
	for(int i = 1; i <= n; ++i)
		for(int j = pos[i]; j > i; ) {
			int x = i;
			while(prime[j - x + 1]) x++;
			pos[a[x]] = j, pos[a[j]] = x;
			v.push_back(make_pair(x, j));
			swap(a[x], a[j]);
			j = x;
		}
	printf("%d\n", v.size());
	for(int i = 0; i < v.size(); ++i)
		printf("%d %d\n", v[i].st, v[i].nd);
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值