题目连接:http://hihocoder.com/problemset/problem/1014
第一次写字典树,首先写了个顶部没有空结点的字典树,- -!!,与别人讨论后发现这样实在是太奇怪了,随后写了个标准一点的字典树,开帖记录。。。
ps:上面的那个网站挺不错的,验证模版什么的太方便了。
第一次代码:
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
struct Trie;
struct node{
int cnt;
Trie *next;
node(){cnt = 0; next = NULL;}
};
struct Trie{
node a[26];
Trie(){}
void insert(char *word);
int find(char *word);
};
void Trie::insert(char *word){
Trie *p = this;
int i;
for(i = 0; i < strlen(word)-1; i++){
if(p->a[word[i]-'a'].next == NULL){
p->a[word[i]-'a'].next = new Trie;
}
p->a[word[i]-'a'].cnt++;
p = p->a[word[i]-'a'].next;
}
p->a[word[i]-'a'].cnt++;
}
int Trie::find(char *word){
Trie *p = this;
int i;
for(i = 0; i < strlen(word)-1; i++){
p = p->a[word[i]-'a'].next;
if(p == NULL) return 0;
}
return p->a[word[i]-'a'].cnt;
}
int n,m;
char s[30];
int main(){
Trie t;
scanf("%d",&n);
for(int i = 0; i < n; i++){
scanf("%s",s);
t.insert(s);
}
scanf("%d",&m);
for(int i = 0; i < m; i++){
scanf("%s",s);
printf("%d\n",t.find(s));
}
return 0;
}
第二次代码:
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
struct Trie{
Trie *a[26];
int cnt;
Trie(){
for(int i = 0; i < 26; i++) a[i] = NULL;
cnt = 0;
}
void insert(char *word);
int find(char *word);
};
void Trie::insert(char *word){
Trie *p = this;
int i;
for(i = 0; i < strlen(word); i++){
if(p->a[word[i]-'a'] == NULL){
p->a[word[i]-'a'] = new Trie;
}
p = p->a[word[i]-'a'];
p->cnt++;
}
}
int Trie::find(char *word){
Trie *p = this;
int i;
for(i = 0; i < strlen(word); i++){
p = p->a[word[i]-'a'];
if(p == NULL) return 0;
}
return p->cnt;
}
int n,m;
char s[30];
int main(){
Trie t;
scanf("%d",&n);
for(int i = 0; i < n; i++){
scanf("%s",s);
t.insert(s);
}
scanf("%d",&m);
for(int i = 0; i < m; i++){
scanf("%s",s);
printf("%d\n",t.find(s));
}
return 0;
}