[Codeforces1148C] Crazy Diamond-- construction

Topic links:

[Codeforces1148C]Crazy Diamond

Subject to the effect:

Gives a $ 1 \ sim n $ is the number required to sort arrangement, each of the two positions can be exchanged if and only if these two positions is greater than the absolute value of the difference is equal to subscript $ \ frac {n} {2} $ . A set of operands required output is not greater than $ $ 5N solution and guaranteed solvable.

Is not considered operational needs of the restrictions, so you want to arrange sorted only the first $ i $ times the $ i $ the index number for that $ i $ swapped click.

Now, with restrictions obviously can not be directly replaced, we consider using other numbers to complete the exchange of these two numbers.

Suppose you want to exchange the two index positions, respectively, and $ X $ $ Y $ and $ y> x $.

When $ \ frac {n} {2} \ when le yx $, can direct exchange.

When $ x> \ frac {n} {2} $, the apparent $ x, y $ can be $ 1 and $ exchange positions:

$ 1, x, y $

$ X, 1 and $

$ And 1 x $

$ 1, and $ x

When $ y \ le \ frac {n} {2} $ time, $ x, y $ can $ and $ n-exchange position, as above.

When $ x \ le \ frac {n} {2}, y> \ frac {n} {2} and yx <\ frac {n} {2} $, the apparently only rely $ 1 $ or $ n-$ can not be completed, However, $ 1 and $ Y $ to exchange $, $ x $ $ and $ n-exchange can be:

$ 1, x, y, n $

$ Y, x, 1, n $

$ Y, n, 1, x $

$ X, n, 1 and $

$ 1, n, x, y $

$ 1, and x, n $

You can find such operation requires $ 5 $ operations for each point up to keep it in its rightful place, so be sure to complete within $ 5n $ operations.

#include<set>
#include<map>
#include<queue>
#include<stack>
#include<cmath>
#include<vector>
#include<cstdio>
#include<bitset>
#include<cstring>
#include<iostream>
#include<algorithm>
#define ll long long
using namespace std;
int n,m;
int a[300010];
int b[300010];
int ans[1500010][2];
int cnt;
void get(int x,int y)
{
	ans[++cnt][0]=x,ans[cnt][1]=y;
	b[a[x]]=y;
	b[a[y]]=x;
	swap(a[x],a[y]);
}
void solve(int x,int y)
{
	if(x==y)return ;
	if(x>y)swap(x,y);
	if(y-x>=m)get(x,Y);
	else if(x>m)
	{
		get(1,x);
		get(1,y);
		get(1,x);
	}
	else if(y<=m)
	{
		get(y,n);
		get(x,n);
		get(y,n);
	}
	else
	{
		get(1,y);
		get(x,n);
		get(1,n);
		get(1,y);
		get(x,n);
	}
}
int main()
{
	scanf("%d",&n);m=n/2;
	for(int i=1;i<=n;i++)
	{
		scanf("%d",&a[i]);
		b[a[i]]=i;
	}
	for(int i=1;i<=n;i++)
	{
		solve(i,b[i]);
	}
	printf("%d\n",cnt);
	for(int i=1;i<=cnt;i++)
	{
		printf("%d %d\n",ans[i][0],ans[i][1]);
	}
}

Guess you like

Origin www.cnblogs.com/Khada-Jhin/p/10962181.html