Face questions
Given a length of n are arranged in a, be exchanged every time the i-th and j-th element of a sequence, if and only if \ (2 \ Times | ij of | \ GEQ n \) , seeking for exchanging programs, so that sequence from small to large sorted
analysis
Our focus is to consider how to change the first x number of i-th position, and try not to undermine the position of the other numbers
We use first, a sequence number n as a springboard, if the distance between the n and n satisfy the conditions to the exchange, or the exchange 1, defined find (x) as x Who should exchange.
1. Find the x and (x) switching, then to Find x (x)
2.find (x) and find (i) exchange of x at this time to find (i)
3.find (i) exchange of i, then x to i
We can find such exchange will only produce in exchange for n number 1, regardless of the number of other location unchanged. We just perform the above operations on operands 2 ~ n-1, and finally we look at a [1] is not 1, then the exchange or need determination (1, n-) to
Code
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<vector>
#define maxn 300005
using namespace std;
int n;
vector< pair<int,int> >ans;
int a[maxn];
int pos[maxn];//值为i的数的位置
inline int find(int x){
if(2*(n-x)>=n) return n;
else return 1;
}
void change(int x,int y){
ans.push_back(make_pair(x,y));
swap(pos[a[x]],pos[a[y]]);
swap(a[x],a[y]);
}
int main(){
scanf("%d",&n);
for(int i=1;i<=n;i++){
scanf("%d",&a[i]);
pos[a[i]]=i;
}
for(int i=2;i<n;i++){
int t=pos[i];
change(t,find(t));
if(find(t)!=find(i)) change(find(t),find(i));
change(i,find(i));
}
if(a[1]!=1) change(1,n);
printf("%d\n",ans.size());
for(auto p : ans){
printf("%d %d\n",p.first,p.second);
}
}