hdoj 1247 trie树

#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;
			}
		}
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值