#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
typedef struct dictor DIC;
DIC *root = NULL;//初始化,呵呵
struct dictor
{
dictor (){ exist = false; memset ( child , 0 , sizeof ( child ) ); }//初始化函数很重要
void insert ( char *ins );
bool find ( const char *ins );
private:
DIC *child[26];
bool exist;
};
//插入函数
void dictor::insert ( char *ins )
{
DIC *cur = root,*now;
int len = strlen ( ins );
for ( int i = 0; i < len; ++ i )
{
if ( cur->child[ ins[i] - 'a' ] != NULL )//如果说这个点已经有元素啦
{
cur = cur->child[ ins[i] - 'a' ];//移动游标
}
else
{
now = new DIC;//新建一个节点
cur->child[ ins[i] - 'a' ] = now;//把这个节点加到trie树中
cur = now;//把当前位置保存下来给游标,用来存放下一个元素
}
}
cur->exist = true;
}
//查找函数
bool dictor::find ( const char *ins )
{
DIC *cur = root;
int len = strlen ( ins );
for ( int i = 0; i < len; ++ i )
{
if ( cur->child[ ins[i] - 'a' ] != NULL )//如果这个点存在
cur = cur->child[ ins[i] - 'a' ];//移动游标
else
return false; //返回失败
}
return cur->exist;//返回cur的存在状态
}
char words[50050][100];
char s1[100],s2[100];
DIC dict;
int main()
{
root=&dict;
int n=0;
while(scanf("%s",words[n])!=EOF)
{
dict.insert(words[n]);
n++;
}
for(int i=0;i<n;i++)//查找每一个数
{
int len=strlen(words[i]);
for(int j=1;j<len;j++)
{
memset(s1,0,sizeof(s1));
memset(s2,0,sizeof(s2));
strncpy(s1,words[i],j);//前j位给s1
strcpy(s2,words[i]+j);//j位以后给s2
if(dict.find(s1)&&dict.find(s2))
{
printf("%s\n",words[i]);break;
}
}
}
}
hdoj 1247 trie树
最新推荐文章于 2022-07-01 19:28:43 发布