您的位置:首页 > 其它

字典树练习(一)hihocoder 1014(求相同前缀的数目)

2015-04-29 10:47 495 查看
题目链接:

http://hihocoder.com/problemset/problem/1014

题意:

给定n个单词,然后我们构成一个字典树,然后再给你m个串,求有多少个单词是以这个串为前缀的。

代码如下:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>

using namespace std;

const int maxn = 100010;

const int max_size = 30;

int id(char c){
return c-'a';
}

struct Trie{
Trie *ch[max_size];
int num;
Trie(){
num = 0;
for(int i=0;i<max_size;i++)
ch[i]=NULL;
}
}*root;

void insert_str(char *s){
Trie *p = root;
p->num++;
for(int i=0; p&&s[i] ; i++){
int u = id(s[i]);
if(p->ch[u]==NULL)
p->ch[u] = new Trie;
p=p->ch[u];
p->num++;
}
}

int find_str(char *s){
Trie *p = root;
for(int i=0;p&&s[i];i++){
int u = id(s[i]);
if(p->ch[u]==NULL) return 0;
p=p->ch[u];
}
return p->num;
}

int main()
{
char s[12];
int n, m;
while(~scanf("%d", &n))
{
root = new Trie;
while(n--){
scanf("%s", s);
insert_str(s);
}
scanf("%d", &m);
while(m--){
scanf("%s", s);
printf("%d\n", find_str(s));
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: