典型的字典树:
//思路:单词是小写的
//1)把所有的单词添加到字典树中
//2)然后针对每一个单词,把这个单词分成2个部分,分别在字典树中查询,如果同时存在则输出该单词,否则继续分成2个部分
#include <iostream>
#include <algorithm>
using namespace std;
#define N 32
#define SIZE 26
#define LISTSIZE 50010
typedef struct WordList_
{
char str[N];
}WordList[LISTSIZE];
typedef struct Node_
{
int is_word;
Node_ * next[SIZE];
Node_()
{
is_word = 0;
for(int i = 0;i < SIZE;i++)
{
next[i] = 0;
}
}
}Node;
Node * root = 0;
WordList diclist;
WordList wlist;
bool cmp(WordList_ a, WordList_ b)
{
return strcmp(a.str, b.str) < 0;
}
int tree_insert(char * word)
{
if (root == 0)
{
root = new Node();
}
int len = strlen(word), i, site;
Node * tmpNode = root;
for(i = 0;i < len;i++)
{
site = word[i] - 'a';
if (tmpNode->next[site] == 0)
{
tmpNode->next[site] = new Node();
}
tmpNode = tmpNode->next[site];
}
tmpNode->is_word = 1;
return 0;
}
int tree_search(char * word)
{
int len = strlen(word);
int site;
Node * tmpNode = root;
for(int i = 0;i < len;i++)
{
site = word[i] - 'a';
if (tmpNode->next[site] == 0)
{
return 0;
}
tmpNode = tmpNode->next[site];
}
return tmpNode->is_word;
}
bool tree_delete(char * str)
{
Node * tmpNode = root;
int len = strlen(str);
int i, site;
for (i = 0;i < len;i++)
{
site = str[i] - '0';
if (tmpNode->next[site] == 0)
{
return 0;
}
tmpNode = tmpNode->next[site];
}
if (tmpNode->is_word == 1)
{
tmpNode->is_word = 0;
}
else
{
return false;
}
return true;
}
void tree_clear(Node * root)
{
if (root == 0)
{
return;
}
int i ;
for ( i = 0;i < 10;i++)
{
if (root->next[i] != 0)
{
Node * tmpNode = root;
root = root ->next[i];
tree_clear(root);
root = tmpNode;
}
}
if (i == 10)
{
delete root;
root = 0;
}
}
int main()
{
int t, n = 0, i, j, k,len;
char left[N], right[N];
int wlistlen = 0;
while (scanf("%s", diclist[n].str) != EOF)
{
tree_insert(diclist[n].str);
n++;
}
for (int i = 0; i < n;i++)
{
len = strlen(diclist[i].str);
if (len < 2)
{
continue;
}
for(j = 1;j < len-1;j++)
{
strncpy(left, diclist[i].str, j);
left[j] = 0;
strncpy(right, diclist[i].str + j, len - j);
right[len - j] = 0;
if (tree_search(left) && tree_search(right))
{
strcpy(wlist[wlistlen++].str, diclist[i].str);
break;
}
}
}
sort(wlist, wlist + wlistlen, cmp);
for (int i = 0;i < wlistlen;i++)
{
printf("%s\n", wlist[i].str);
}
return 0;
}