题目来源:poj 3087
题目意思是 先给你两个长度一样的初始状态字符串s1,s2和一个大小为两倍的最终状态的s12,按照s2的第一个先放在s12第一个再依次是s1,s2,s1…,排完后再按照长度前一半是s1新状态,后一半是s2新状态, 重复以上操作,看得到s12是否有和 最初给的最终状态的s12相同的,有输出步数,没有就输出-1。
#include <iostream>
#include <string>
#include <map>
#include <queue>
#include <algorithm>
using namespace std;
struct node
{
string s1; //前半个字符串
string s2; //后半个字符串
int step;
} start;
map<string, bool> M;
string res;
void BFS(int count, int n)
{
queue<node> Q;
Q.push(start);
if (start.s1 == res.substr(0, n) && start.s2 == res.substr(n))
{
cout << count << ' ' << 0 << endl;
return;
}
while (!Q.empty())
{
node top = Q.front();
Q.pop();
string s = "";
for (int i = 0; i < n; i++)
{
s += top.s2[i];
s += top.s1[i];
}
if (M[s] == false)
{
if (s == res)
{
cout << count << ' ' << top.step + 1 << endl;
return;
}
node temp;
temp.s1 = s.substr(0, n);
temp.s2 = s.substr(n);
temp.step = top.step + 1;
M[s] = true;
Q.push(temp);
}
else
{
cout << count << ' ' << -1 << endl;
return;
}
}
}
int main()
{
int T;
cin >> T;
int n;
int count = 1;
while (T--)
{
cin >> n;
cin >> start.s1 >> start.s2;
start.step = 0;
cin >> res;
BFS(count, n);
count++;
M.clear();
}
return 0;
}
Tips:
- 可以用STL中string容器的substr函数找到字符串中的子串。比如
s1 = “Hello World”,则s1.substr(0,5) = “Hello”。- 可以直接用 "+"对字符串进行相加:如s1 = “abc”,s2 = “a”,s1 += s2。
则s1 = “abca”。