hdu 1251 统计难题 字典树
2014-03-17 15:25
183 查看
trie树,指针模式更优雅
#include<stdio.h>
#include<string.h>
struct node{
int cnt;
node *childs[26];
node(){
cnt=0;
for(int i=0;i<26;i++)
childs[i]=NULL;
}
};
node *rt=new node();
node *cur,*next;
void insert(char *str){
cur=rt;
int len=strlen(str),t;
for(int i=0;i<len;i++){
t=str[i]-'a';
if(cur->childs[t]==NULL){
next=new node();
cur->childs[t]=next;
}
else{
next=cur->childs[t];
}
next->cnt++;
cur=next;
}
}
int search(char *str){
cur=rt;
int len=strlen(str),t;
for(int i=0;i<len;i++){
t=str[i]-'a';
if(cur->childs[t]==NULL)
return 0;
cur=cur->childs[t];
}
return cur->cnt;
}
int main(){
char str[20];
while(gets(str)&&str[0])
insert(str);
while(gets(str))
printf("%d\n",search(str));
}
#include<stdio.h>
#include<string.h>
struct node{
int cnt;
node *childs[26];
node(){
cnt=0;
for(int i=0;i<26;i++)
childs[i]=NULL;
}
};
node *rt=new node();
node *cur,*next;
void insert(char *str){
cur=rt;
int len=strlen(str),t;
for(int i=0;i<len;i++){
t=str[i]-'a';
if(cur->childs[t]==NULL){
next=new node();
cur->childs[t]=next;
}
else{
next=cur->childs[t];
}
next->cnt++;
cur=next;
}
}
int search(char *str){
cur=rt;
int len=strlen(str),t;
for(int i=0;i<len;i++){
t=str[i]-'a';
if(cur->childs[t]==NULL)
return 0;
cur=cur->childs[t];
}
return cur->cnt;
}
int main(){
char str[20];
while(gets(str)&&str[0])
insert(str);
while(gets(str))
printf("%d\n",search(str));
}
相关文章推荐
- HDU 1251:统计难题【字典树 & string+map】
- hdu 1251 统计难题(字典树)
- HDOJ/HDU 1251 统计难题(字典树啥的~Map水过)
- hdu 1251 统计难题 字典树裸题
- hdu1251 统计难题 (字典树查找)
- hdu 1251 统计难题 (字典树)
- hdu1251 统计难题 字典树
- [HDU 1251] 统计难题(字典树)
- HDU-1251 统计难题(字典树+map)
- hdu1251 统计难题(字典树)
- HDU 1251 统计难题 字典树
- HDU 1251 统计难题 字典树
- hdu 1251 统计难题 字典树第一题。
- hdu 1251 统计难题 (字典树)
- 字典树 统计难题HDU 1251
- HDU 1251 统计难题 字典树入门(Trie)
- hdu 1251 统计难题 字典树解释 +字典树模板
- HDOJ/HDU 1251 统计难题(字典树啥的~Map水过)
- hdu 1251 统计难题 字典树入门
- hdu 1251 统计难题 字典树