题意:
查找由两个单词拼接组成的单词,并输出这个单词。(可以由同一个两次拼接组成,如: adad是由ad两次拼接组成)
#include<iostream>
#include<cstdio>
#include<cstring>
#include<set>
#include<map>
#include<vector>
#include<cctype>
#include<algorithm>
using namespace std;
const int maxn = 1e5+10;
int tr[maxn][26];
int len[maxn]; //存储第i个单词长度
bool v[maxn]; //标记单词
int tot,root,k;
char s[maxn][20],str1[20],str2[20];
void insert()
{
len[k] = strlen(s[k]);
root = 0;
for(int i=0;i<len[k];i++)
{
int id = s[k][i]-'a';
if(!tr[root][id])
tr[root][id] = ++tot;
root = tr[root][id];
}
v[root] = true;
}
bool find(char *p)
{
root = 0;
for(int i=0;p[i];i++)
{
int x = p[i]-'a';
if(!tr[root][x])
return false;
root = tr[root][x];
}
if(v[root])
return true;
else
return false;
}
int main()
{
tot = 0;
k = 0;
while(~scanf("%s",s[k]))
{
insert();
k++;
}
for(int i=0;i<k;i++) //第几个单词
{
for(int j=1;j<len[i];j++) //将这个单词分成两个
{
memset(str1,0,sizeof(str1)); //不初始化会发生错误
memset(str2,0,sizeof(str2));
strncpy(str1,s[i],j);
strncpy(str2,s[i]+j,len[i]-j);
if(find(str1) && find(str2)) //存在
{
printf("%s\n",s[i]);
break;
}
}
}
return 0;
}