分析:复合词的写法有很多种,可以用STL集合写,也可以直接使用字符串来处理(效率低,会超时),但是字典树的效率无疑对着个体来说是非常高的,只需保留可能的前缀,再去找词的剩余部分是否存在即可,降低了查找的次数,但字典树的高效率来源于高空间,以空间换时间这是ACM中常用的方法
集合或字符串使用见:http://blog.csdn.net/qq_32036091/article/details/50201121
Trie 代码:
#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
const int MAXN=26;
const int MAX=50005;
char word[MAX][26];
struct TrieNode
{
bool value;
TrieNode *next[MAXN];
TrieNode() //初始化函数
{
value=false;
memset(next,0,sizeof(next));
}
};
void Insert(node *root,char *s)
{
int i=0;
TrieNode *p=root;
while(s[i])
{
int k=s[i++]-'a';
if(p->next[k]==NULL)
p->next[k]=new TrieNode();
p=p->next[k];
}
p->is=true; //该结点是单词的尾
}
bool Search(node *root,char s[])
{
int i=0,top=0,stack_1[1000];
node *p=root;
while(s[i])
{
int k=s[i++]-'a';
if(p->next[k]==NULL) return 0;
p=p->next[k];
if(p->is && s[i]) //找到该单词含有子单词的分隔点
stack_1[top++]=i; //入栈
}
while(top) //从可能的分割点去找
{
bool ok=true;
i=stack_1[--top];
p=root;
while(s[i])
{
int k=s[i++]-'a';
if(p->next[k]==NULL)
{
ok=false;
break;
}
p=p->next[k];
}
if(ok && p->is) //找到最后,并且是单词的
return 1;
}
return 0;
}
int main()
{
int i=0;
TrieNode *root=new node();
while(gets(word[i]) && strcmp(word[i],"*"))
{
Insert(root,word[i]);
i++;
}
for(int j=0;j<i;j++)
if(Search(root,word[j]))
printf("%s\n",word[j]);
return 0;
}