这题应该不是搜索,勉强算个hash把。其实是个水模拟。。。
判断-1的方法就是,看是否是得到了以前出现过的字符串,所以用set或者map都可以。
这里用的是set。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <set>
using namespace std;
set<string> st;
int n;
char *shuffle(char *str2,char *str1)
{
int i,j;
char str[3000];
i=0;
j=0;
while (i != n)
{
str[j]=str1[i];
str[j+1]=str2[i];
j+=2;
i++;
}
str[j]='\0';
return str;
}
int main()
{
int T,i,j,cnt,prob;
char str1[2000],str2[2000],str3[3000],ts[3000];
scanf("%d",&T);
prob=1;
while (T--)
{
scanf("%d",&n);
getchar();
scanf("%s%s%s",str1,str2,str3);
strcpy(ts,shuffle(str1,str2));
st.clear();
st.insert(ts);
cnt=1;
printf("%d ",prob);
prob++;
if (strcmp(ts,str3) == 0)
{
printf("%d\n",cnt);
continue;
}
while (1)
{
strcpy(ts,shuffle(ts,ts+n));
cnt++;
if (strcmp(ts,str3) == 0)
{
printf("%d\n",cnt);
break;
}
if (st.find(ts) != st.end())
{
printf("-1\n");
break;
}
st.insert(ts);
}
}
}
字符串模拟
本文介绍了一种通过交替合并两个字符串并检查循环是否能形成特定目标字符串的算法。使用了哈希集合来跟踪已产生的字符串,以此判断循环是否会导致无限重复的状态。
514

被折叠的 条评论
为什么被折叠?



