King's Task - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)
![](https://img-blog.csdnimg.cn/img_convert/0c60eccd637840498315bdda1166c01b.png)
1.将全部相邻的数交换,
2将前半段和 后半段的数交换
如果连续进行一种操作两次就会相互抵消,那么答案一定是两种操作交替进行的
看看哪个操作先进行,所得的结果会更优
#include <bits/stdc++.h>
#include <iostream>
#include <cstring>
#include <algorithm>
#include <vector>
#include <set>
#define x first
#define int long long
#define y second
#define ios ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
using namespace std;
typedef long long LL;
typedef pair<int,int> PII;
typedef pair<char,int> PCI;
typedef pair<LL,LL> PLL;
//typedef __int128 i128;
typedef unsigned long long ULL;
const int N=2e5+10,INF = 1e9 ,mod = 1e9 + 7 ;
const double eps = 1e-7;
int n,a[N],b[N],c[N];
bool same(int a[],int b[])
{
for(int i=1;i <= 2* n ; i++ )
if(a[i] != b[i]) return 0;
return 1;
}
int ans=INF;
void solve()
{
cin >> n;
for(int i=1;i <= 2 * n ;i ++ )
{
int t;cin >> t;a[i] = b[i] = c[i] = t;
}
bool flag =1;
if(!is_sorted(a+1,a+2*n + 1)) flag =0;
if(flag)
{
cout << 0 << endl;return;
}
int op=0,id =1;
while(!same(a,b) || !op)//先进行第一种操作
{
op ++;
if(id)
{
for(int i=1;i+1<=2 *n ;i += 2)
swap(b[i],b[i + 1] );
}
else
{
for(int i=1;i<=n; i++ )
swap(b[i],b[i + n]);
}
id ^= 1;
if(is_sorted(b+1,b+1+2*n))
{
ans =min(ans,op);break;
}
}
id = op = 0 ;
while(!same(a,c) || !op)
{
op ++;
if(id)
{
for(int i=1;i+1<=2 *n ;i += 2)
swap(c[i],c[i + 1] );
}
else
{
for(int i=1;i<=n; i++ )
swap(c[i],c[i + n]);
}
id ^= 1;
if(is_sorted(c+1,c+1+n*2))
{
ans = min(ans,op);break;
}
}
if(ans== INF ) ans = -1;
cout << ans << endl;
}
signed main()
{
// freopen("1.txt","r",stdin);
ios
LL T=1;
// cin>>T;
while(T -- )
{
solve();
}
return 0;
}