CodeForces 1510K King‘s Task DFS暴力搜索

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;
}
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

球王武磊

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值