您的位置:首页 > 其它

Hiho+Trie数求字符串前缀的典型模板

2016-05-02 22:03 375 查看
点击打开链接
#include<stdio.h>
#include<stdlib.h>
#include<iostream>
#include<string.h>
#include<cstring>
#include<string>
#include<math.h>
#include<algorithm>
#define LL long long
#define inf 0x3f3f3f3f
#define mod 1e9+7
using namespace std;
struct Tire
{
int num;
Tire* next[26];
Tire(){
num=0;
int i;
for(i=0; i<26; i++)
next[i] = NULL;
}
} tree;
void Insert(char word[])
{
Tire* p = &tree;
int i;
for(i=0; word[i]; i++){
int t = word[i]-'a';
if(p->next[t]==NULL)
p->next[t] = new Tire;
p = p->next[t];
p->num++;
}
}
int Find(char word[])
{
Tire* p = &tree;
int i;
for(i=0; word[i]; i++){
int t = word[i]-'a';
if(p->next[t]==NULL)
return 0;
p = p->next[t];
}
return p->num;
}
int main()
{
int n;
char word[11];
///字典
scanf("%d",&n);
gets(word);
while(n--){     ///读取单词n次
gets(word);
Insert(word);    ///将单词插入到字典树中
}
///询问
scanf("%d",&n);
gets(word);    ///将回车读入
while(n--){
gets(word);
printf("%d\n",Find(word));    ///查询以word为前缀的单词出现过几次
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: