您的位置:首页 > 其它

hiho一下第二周 Trie树

2015-10-06 23:30 423 查看
题目链接:http://hihocoder.com/problemset/problem/1014

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
using namespace std;

const int maxn = 1e6 + 5;  // 1e5 * 10 (1e5个单词 * 单词长度 (<= 10))
const int N = 26;

int le;
char str
;

struct Trie
{
int cnt;
int next
;
void init() {
cnt = 0;
memset(next, -1, sizeof(next));
}
}T[maxn];

void Build(char *s)
{
int i = 0, p = 0;
while (s[i]) {
int x = s[i] - 'a';
if (T[p].next[x] == -1) {
T[le].init();
T[p].next[x] = le++;
//      printf("T[%d].next[%d] = %d,  ", p, x, T[p].next[x]);
}
p = T[p].next[x];
T[p].cnt++;
//     printf("T[%d].cnt = %d\n", p, T[p].cnt);
i++;
}
}

void Query(char *s)
{
int i = 0, p = 0;
while (s[i]) {
int x = s[i] - 'a';
if (T[p].next[x] == -1) {
puts("0");
return ;
}
p = T[p].next[x];
i++;
}
printf("%d\n", T[p].cnt);
}

int main()
{
int n, m;
#ifndef ONLINE_JUDGE
freopen("in.txt", "r", stdin);
#endif // ONLINE_JUDGE

while (scanf("%d", &n) != EOF) {
le = 1;
T[0].init();   // !root
while (n--) {
scanf("%s", str);
Build(str);
}
scanf("%d", &m);
while (m--) {
scanf("%s", str);
Query(str);
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: