版权声明:反正也没有人会转,下一个 https://blog.csdn.net/drtlstf/article/details/82929852
Description
给定两个长度为len的字符串s1和s2, 接着给出一个长度为len*2的字符串s12。
将字符串s1和s2通过一定的变换变成s12,找到变换次数
变换规则如下:
假设s1=12345,s2=67890
变换后的序列 s=6172839405
如果s和s12完全相等那么输出变换次数
如果不完全相等,s的前半部分作为s1,后半部分作为s2,重复上述过程。
Input
第一行给出T(1≤T≤1000),代表有T组数据,每组数据首先给出len(1≤len≤100),接着给出两个长度为len的字符串s1 s2 然后给出长度为len*2的字符串s12。
Output
首先输出处理数据组的编号(编号从1开始)
再输出变换次数并换行。
注意两个数字之间有空格。
对于变换次数,如果无需变换直接得到s12,那么输出0,如果无论怎么变换都不会得到s12,那么输出 -1。
Sample Input
2
4
AHAH
HAHA
HHAAAAHH
3
CDE
CDE
EEDDCC
Sample Output
1 2
2 -1
直接模拟,如果反而到了之前出现的状态,那显然不可能。
#include <iostream>
#include <string>
#include <set>
using namespace std;
string s1, s2, s3, temp;
set<string> s;
int main(int argc, char** argv)
{
int t, n, res, _case = 0, i;
scanf("%d", &t);
while (t--)
{
res = 0;
scanf("%d", &n);
cin >> s1 >> s2 >> s3;
printf("%d ", ++_case);
if (s1 + s2 == s3)
{
printf("0\n");
continue;
}
temp = "";
for (i = 1; i <= n + n; ++i)
{
temp += ' '; // 防止下标越界
}
s.clear();
s.insert(s1 + s2);
for ( ; ; ) // 模拟
{
for (i = 0; i < n; ++i)
{
temp[i+i] = s2[i];
temp[i+i+1] = s1[i];
}
++res;
if (temp == s3)
{
printf("%d\n", res);
break;
}
if (s.count(temp)) // 如果回到了之前到状态,那么显然不可能做到
{
printf("-1\n");
break;
}
s.insert(temp);
s1 = temp.substr(0, n);
s2 = temp.substr(n, n);
}
}
return 0;
}