您的位置:首页 > 其它

hihocoder 1014 Trie树 字典树模版题

2015-03-16 20:26 387 查看
题目连接: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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: