Trie树的应用

补充知识:binary_search 函数既可以用来普通数字数组的二分查找,也能用来二分查找字符串数组,但前提是字符串数组是按字典序的顺序排好,不过貌似在普通数组中,排序后的数组可直接用binary_search( first,last, value)(应该是默认从小到大排序),但对于字符串数组,用binary_search要自定义一个与其排序规则相同的比较函数

例如:bool comp( string a,string b) {  return a<b;  }

           binary_search(first,last, value, comp);

例题:

 

Description

A hat’s word is a word in the dictionary that is the concatenation of exactly two other words in the dictionary.
You are to find all the hat’s words in a dictionary.

 

Input

Standard input consists of a number of lowercase words, one per line, in alphabetical order. There will be no more than 50,000 words.
Only one case.

 

Output

Your output should contain all the hat’s words, one per line, in alphabetical order.

 

Sample Input

 

a ahat hat hatword hziee word

 

 

Sample Output

 

ahat hatword

 

题意:输入若干个字符串(按照字典序顺序输入),输出其中所有能够表示成s=a+b(a、b、s均属于其中)中 的s,输出也按字典序输出。

 

 

分析:

为了优化时间,采用Trie树构造字典,遇到子字符串的时候,查询剩余字符组成的字符串在原字符串数组中是否存在,利用二分查找。

 

 

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cstdlib>
using namespace std;
#define branchNum 26
char ch[50001][100]={'\0'};
int length;
bool comp(string a,string b)
{
    return a<b;
}
struct Node
{
    bool isStr;
    Node *next[branchNum];
    Node():isStr(false)
    {
        memset(next,NULL,sizeof(next));
    }
};
Node *root=new Node;
bool Search(char *str)
{
    if(binary_search(ch,ch+length,str,comp)) return true;
    else return false;

}
void Insert(char *str)
{
    char save[100]={'\0'};
    int tag=0;
    strcpy(save,str);
    int length=strlen(str);
    Node *tmp=root;
    while(*str)
    {
        int m=*str-'a';
        if(tmp->next[m]!=NULL)
        {
            tmp=tmp->next[m];
            if(tmp->isStr==true)
            {
                if(Search(str+1)&&tag==0) //注意设置tag防止该字符串是多对字符串的结合,防止重复输出
                 {
                     cout<<save<<endl;
                     tag=1;
                 }
            }
        }
        else
        {
            Node *t=new Node;
            tmp->next[m]=t;
            tmp=t;
        }
        str++;
    }
    tmp->isStr=true;
}

int main()
{
    int i=0;
    while(cin>>ch[i]) i++;
    length=i;
    for(int k=0;k<length;k++)
    {
         Insert(ch[k]);
    }

    return 0;
}

 

 

 

 

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值