您的位置:首页 > 其它

Trie树的应用

2016-07-28 00:37 204 查看
补充知识: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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Trie 字典树