H.排列还原

版权声明:晓程原创 https://blog.csdn.net/qq_43469554/article/details/88129196

给定一个包含 1 ~ n的排列 p1,p2,p3,⋯,pn ,现在我们通过一些操作把排列还原成 1,2,3⋯,n。每次操作你可以选择一个任意的k(1≤k≤n),然后翻转 p1,p2,⋯,pk,求最少需要次操作。比如对于排列1,5,4,3,2,我们可以先翻转前面 5 个数变成 2,3,4,5,1,然后翻转前 4 个数边城 5,4,3,2,1,然后再翻转前 5 个数变成 1,2,3,4,5,用三次操作完成了排列还原。

输入格式

输入第一行一个整数 n(1≤n≤10)。接下来一行输入 n 个整数 pi(1≤pi ≤n),保证 pi 不相同。

输出格式

输出一行一个整数表示最小的操作次数。如果不能还原输出 −1。

样例输入:
5
1 5 4 3 2
样例输出:
3

#include <iostream>
#include <string>
#include <map>
#include <queue>
using namespace std;
map<string, int> mp;
int n;
int bfs(string st, string en)
{
	if (st == en)
	{
		return 0;
	}
	queue<string> q;
	q.push(st);
	mp[st] = 0;
	while (!q.empty())
	{
		string s = q.front();
		q.pop();
		for (int i = 1; i < n; i++)
		{
			string tt = s;
			for (int j = 0, k = i; j < k; j++, k--)//保证每一种交换情况 
			{
				swap(tt[j], tt[k]);
			}
			if (tt == en)
			{
				return mp[s] + 1; 
			}
			if (!mp.count(tt))
			{
				mp[tt] = mp[s] + 1;
				q.push(tt);
			}
		}
	}
}
int main()
{
	string s ="", e = "";
	cin >> n;
	for (int i = 1; i <= n; i++)
	{
		int x;
		cin >> x;
		s += to_string(x);//将整型转化为字符串,返回字符串
		e += to_string(i);
	}
	cout << bfs(s, e) << endl;
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_43469554/article/details/88129196
今日推荐