题意:查找单词看有没有单词是另两个的组合而成
思路:字典树,先建好树,然后在搜索,搜索时将每个单词都不同分割暴力搜索
不能边插便问,因为顺序是随即的,有可能漏,如a ,ahat,hat这样ahat就漏掉了,所以只能全部建树然后从头遍历到尾
如果是按照长度小到大给你的,可以边插边问
实质还是查单词,只不过多查了几个而已
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
struct Tree
{
bool flag;
struct Tree * child[26];
}Tri[500005];
int alloc = 0;
struct Tree *creat_node()
{
Tree * p;
p = &Tri[alloc++];
int i;
for(i = 0; i < 26; i++)
{
p -> child[i] = NULL;
}
p -> flag = false;
return p;
}
void insert(Tree **p,char *str)
{
int i,len;
len = strlen(str);
Tree * q;
q = *p;
for(i = 0; i < len; i++)
{
if(q -> child[str[i]-'a'] != NULL)
{
q = q -> child[str[i]-'a'];
}
else
{
q -> child[str[i]-'a'] = creat_node();
q = q -> child[str[i]-'a'];
}
}
q -> flag = true;
}
bool Find(Tree ** p,char *str)
{
int i,len;
Tree * q;
q = *p;
len = strlen(str);
if(len == 0)
return false;
for(i = 0; i < len; i++)
{
if(q -> child[str[i]-'a'] != NULL)
{
q = q -> child[str[i]-'a'];
}
else
{
return false;
}
}
if(q -> flag == true)
return true;
else
return false;
}
int main()
{
char c[50005][20];
int n = 0;
Tree *root;
root = creat_node();
while(scanf("%s",c[n]) != EOF)
{
insert(&root,c[n]);n++;
}
int i,j,k,sum = 0;
for(i = 0 ; i < n;i++)
{
int len = strlen(c[i]);
for(j = 0; j < len; j++)
{
char str1[100];
char str2[100];
for(k =0; k <= j; k++)
{
str1[k] = c[i][k];
}
str1[k] = '\0';
strcpy(str2,c[i]+k);
if(Find(&root,str1) && Find(&root,str2))
{
printf("%s\n",c[i]);break;
}
}
}
return 0;
}