标签:出现 get 考虑问题 include scribe -o 组成 代码 数字
输入包含多组测试数据,每组测试数据由两行组成。 第一行为一个整数N,代表字符串的长度(2<=N<=13)。 第二行为一个仅由0、1、2组成的,长度为N的字符串。
对于每组测试数据,若可以解出密码,输出最少的移位次数;否则输出-1。
5 02120
1
这个题目的关键点就在于交换位置,所有的可能结果都是通过交换形成的,并且所求的也是交换所需要的最少次数。所以从交换次数着手,可以这么考虑问题:
每次交换一次得到一个字符串,如果已经出现过则不用考虑,如果没有出现过,则判断是否有出现过“2012”。有的话交换次数则为原来字符串的交换次数加上1。
#include <iostream>
#include <cmath>
#include <map>
#include <string>
#include <queue>
using namespace std;
string swap(string s,int i)
{
string ans = s;
char temp = s[i];
ans[i] = ans[i + 1];
ans[i + 1] = temp;
return ans;
}
int main()
{
int len;
string str;
string target = "2012";
while(cin >> len >> str)
{
int ans = 0;
map<string,int> mp;
queue<string> q;
mp[str] = 0;
q.push(str);
while(!q.empty())
{
string temp = q.front();
// cout << temp << endl;
q.pop();
if(temp.find(target) != -1)
{
ans = mp[temp];
break;
}
else
{
for(int i = 0;i < len - 1;i++)
{
string now = swap(temp,i);
if(mp.find(now) == mp.end())
{
mp[now] = mp[temp] + 1;
q.push(now);
}
}
}
}
cout << ans << endl;
}
return 0;
}
标签:出现 get 考虑问题 include scribe -o 组成 代码 数字
原文地址:https://www.cnblogs.com/tracy520/p/8836499.html