题目链接: Problem 1004 | Trie
题意:给n个单词,m次查询,问以某个字符串为前缀的单词有多少个.
题解:写个Trie树水一下,第一写,所以才找简单的搞…
细节处理:
- 数据范围:100k单词,每个单词长度不过10,字典字母表不超过26.
- 单词可能重复,在实现中尽可能避免增加标记,以节省内存.
- 单词字母可能不是英文字母(题中指明"火星文单词"),不知道测试数据有没有这么弄,总之根据题意来是允许非英文字母的出现的.当然应该不存在空格符,否则无法分别不同单词间的连接.
- 询问的前缀可能原字典中不存在,这点题目的测试数据已经提示.
代码:
#include <cstdio>
#include <cstring>
#include <vector>
#include <map>
#include <algorithm>
using namespace std;
const int LEN = 26;
map<char, int> mmap;
int dic;
struct node {
int sum;
int a[LEN];
node* son[LEN];
void clear() {
memset(a, 0, sizeof(a));
memset(son, 0, sizeof(son));
sum = 0;
}
node() {
clear();
}
};
void clear(node* T) {
if (T == NULL) return;
for (int i = 0; i < LEN; ++i) {
if (T->son[i]) {
clear(T->son[i]);
}
}
T->clear();
}
static char word[LEN];
static int len;
void add(node* &T, char idx) {
//printf("add %c,%d\n", word[idx], mmap[word[idx]]);
if (T == NULL) {
T = new node();
}
if (idx < len) {
add(T->son[mmap[word[idx]]], idx + 1);
}
++(T->sum);
}
int query(node* &T, char idx) {
//printf("visit %d\n", idx);
if (idx == len) {
return T->sum;
} else {
//return query(T->son[word[idx]], ++idx);
char to_go = mmap.count(word[idx]) ? mmap[word[idx]] : -1;
if ((~to_go) && T->son[to_go]) {
return query(T->son[to_go], ++idx);
} else {
return 0;
}
}
}
void rm(node* &T) {
if (T) {
for (int i = 0; i < dic; ++i) {
rm(T->son[i]);
}
delete T;
T = NULL;
}
}
int id = 0;
char tmp[LEN];
void visit(node* &T, char name[], int c) {
if (T == NULL) return;
bool sc = true;
for (int i = 0; i < dic; ++i) {
if (T->son[i]) {
sc = false;
name[c] = tmp[i];
visit(T->son[i], name, c + 1);
}
}
if (sc) {
name[c] = '\0';
puts(name);
}
}
int main() {
node* root = NULL;
int n, m;
while (~scanf(" %d", &n)) {
mmap.clear();
dic = 0;
while (n--) {
scanf(" %s", word);
len = strlen(word);
for (int j = 0; j < len; ++j) {
if (mmap.count(word[j]) == 0) {
mmap[word[j]] = dic++;
//tmp[dic - 1] = word[j];
}
}
add(root, 0);
//char name[LEN];
//int c = 0;
//visit(root, name, c);
}
scanf(" %d", &m);
while (m--) {
scanf(" %s", word);
len = strlen(word);
printf("%d\n", query(root, 0));
}
rm(root);
}
return 0;
}
题目不难,但是写链表的话调试起来就有点吃力,费了不少时间…