主题思想 : Tries , 在每个非空节点,记录经过它的字符串的个数。
核心方法是 Tries 的put ,get 和collect 方法。
const int R=26;
struct Node{
int val=0;
Node* next[R];
Node(){
val=0;
//very import
memset(next,NULL,sizeof(next));
}
};
Node* root;
int ans=0;
void put(char key[]){
Node *x=root;
int d=0;
char c;
while(d<strlen(key)){
char c=key[d];
if(x->next[c-'a']==NULL){
x->next[c-'a']=new Node();
}
x=x->next[c-'a'];
x->val++;
d++;
}
}
Node* get(char key[]){
Node *x=root;
int d=0;
char c;
while(x!=NULL){
if(d==strlen(key)) {
return x;
}
c=key[d];
x=x->next[c-'a'];
d++;
}
return NULL;
}
int collect(Node *x){
ans=0;
if(x==NULL) return 0;
ans+=x->val;
}
void prefix(char key[]){
ans=0;
collect(get(key));
}
,本来报RE ,,结果使用memest 语句 对Node* 数组 next 进行了初始化,就不报错了。
AC代码:
#include <iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<queue>
using namespace std;
const int R=26;
struct Node{
int val=0;
Node* next[R];
Node(){
val=0;
//very import
memset(next,NULL,sizeof(next));
}
};
Node* root;
int ans=0;
void put(char key[]){
Node *x=root;
int d=0;
char c;
while(d<strlen(key)){
char c=key[d];
if(x->next[c-'a']==NULL){
x->next[c-'a']=new Node();
}
x=x->next[c-'a'];
x->val++;
d++;
}
}
Node* get(char key[]){
Node *x=root;
int d=0;
char c;
while(x!=NULL){
if(d==strlen(key)) {
return x;
}
c=key[d];
x=x->next[c-'a'];
d++;
}
return NULL;
}
int collect(Node *x){
ans=0;
if(x==NULL) return 0;
ans+=x->val;
}
void prefix(char key[]){
ans=0;
collect(get(key));
}
int main()
{
root=new Node();
char s[15];
int n=0;
while(gets(s)){
if(strcmp(s,"")==0)break;
n++;
put(s);
}
while(gets(s)){
prefix(s);
printf("%d\n",ans);
}
return 0;
}

本文介绍了一种使用Trie树(字典树)来高效处理字符串集合的方法,特别关注于如何通过Trie树的节点来记录字符串的出现次数,并实现字符串的插入、查找及前缀统计等功能。
1016

被折叠的 条评论
为什么被折叠?



