CodeForces 1510K King’s Task
【题目描述】
The brave Knight came to the King and asked permission to marry the princess. The King knew that the Knight was brave, but he also wanted to know if he was smart enough. So he asked him to solve the following task.
There is a permutation pi of numbers from 1 to 2n. You can make two types of operations.
Swap p1 and p2, p3 and p4, …, p2n−1 and p2n.
Swap p1 and pn+1, p2 and pn+2, …, pn and p2n.
The task is to find the minimal number of operations required to sort the given permutation.
The Knight was not that smart actually, but quite charming, so the princess asks you to help him to solve the King’s task.
Input
The first line contains the integer n (1≤n≤1000). The second line contains 2n integers pi — the permutation of numbers from 1 to 2n.
Output
Print one integer — the minimal number of operations required to sort the permutation. If it is impossible to sort the permutation using these operations, print −1.
【测试样例】
样例1输入
3
6 3 2 5 4 1
样例1输出
3
样例2输入
2
3 4 2 1
样例2输出
-1
样例3输入
4
1 2 3 4 5 6 7 8
样例3输出
0
Note
In the first example, you can sort the permutation in three operations:
Make operation 1: 3,6,5,2,1,4.
Make operation 2: 2,1,4,3,6,5.
Make operation 1: 1,2,3,4,5,6.
【解题思路】
这道题数据范围很小,我们可以直接采取DFS暴力搜索。我们用vector可以比较方便地存取当前数组,用一个map来记录当前数组状态是否已出现过。如果遇到之前已经搜索到的状态,则结束当前搜索。使用ans来记录答案,如果达到排好序的状态,且需要的步数比ans少,则更新ans的值。如果ans没有被更新过(这里初始设为inf),说明不能实现排序,输出-1。
【AC代码】
#include <iostream>
#include <cstdio>
#include <vector>
#include <map>
using namespace std;
const int inf=1999999999;
int n,ans=inf;
map<vector<int>,int> mp;
void dfs(vector<int> a,int time)
{
int flag=1;
for(int i=0;i<2*n;i++)
{
if(a[i]!=i+1)
{
flag=0;
break;
}
}
if(flag==1)
{
if(time<ans)
ans=time;
}
vector<int> t1;
for(int i=0;i<2*n;i+=2)
{
t1.push_back(a[i+1]);
t1.push_back(a[i]);
}
if(!mp.count(t1))
{
mp[t1]=1;
dfs(t1,time+1);
mp.erase(t1);
}
vector<int> t2;
for(int i=n;i<2*n;i++)
t2.push_back(a[i]);
for(int i=0;i<n;i++)
t2.push_back(a[i]);
if(!mp.count(t2))
{
mp[t2]=1;
dfs(t2,time+1);
mp.erase(t2);
}
}
int main()
{
cin>>n;
vector<int> a(2*n);
for(int i=0;i<2*n;i++)
cin>>a[i];
mp[a]=1;
dfs(a,0);
if(ans==inf)
cout<<"-1"<<endl;
else
cout<<ans<<endl;
return 0;
}