hdu1251-统计难题 点击打开题目
这道题目很典型,给你一些很短但很密的字符串,完了让你查询某一个前缀,问字典树里有多少个单词拥有该前缀,统计,在构建的时候,没经过一个字母就给它的count+1,最后统计给出的子串最后一个字母的count就可以了,如果该子串不存在,那么就输出0.
这道题目特别搞的就是那个count计数,初始值为多少合适?什么是候+1,这要好好考虑一下,基本上能过样例的话就能a。
#include
#include
#include
#define MAXX 26
typedef struct TrieNode /**Trie结点声明*/
{
int countt;
struct TrieNode *next[MAXX]; /**儿子分支*/
}Trie;
void ins(Trie *root, char *s )
{
if(root==NULL||*s=='\0')
return;
int i;
Trie *p=root;
while(*s!='\0')
{
/**printf("i: %d\n", *s-'a');*/
if(p->next[*s-'a']==NULL) /**如果不存在,则建立结点*/
{
Trie *temp=( Trie* )malloc(sizeof(Trie));
for(i=0;i
next[i]=NULL;
}
temp -> countt = 1 ;
p->next[*s-'a'] = temp ;
p = p->next[ *s - 'a' ] ;
}
else
{
p = p->next[ *s - 'a' ] ;
p -> countt++ ;
}
s ++ ;
}
}
int searchh(Trie *root , const char *s) /**查找某个单词是否存在 并且返回它的译文的指针*/
{
Trie *p=root;
while(p!=NULL&&*s!='\0')
{
p=p->next [*s - 'a' ];
s++;
}
if(p!=NULL){
return p->countt ;
}
else{
return 0 ;
}
}
void del(Trie *root) /**释放整个字典树占的堆区空间*/
{
int i;
for( i=0 ; i < MAXX ; i++ )
{
if(root->next[i]!=NULL)
{
del(root->next[i]);
}
}
free(root);
}
int main()
{
char getss[12];
Trie* root ;
int i ;
root = ( Trie * ) malloc( sizeof(Trie) ) ;
for( i = 0 ; i < MAXX ; i++ ){
root -> next[ i ] = NULL ;
}
root -> countt = 0 ;
fgets(getss,sizeof(getss),stdin);
getss[strlen(getss)-1]='\0';
while(getss[0]!='\0'){
ins( root , getss ) ;
fgets(getss,sizeof(getss),stdin);
getss[strlen(getss)-1]='\0';
}
while( scanf ("%s",getss) != EOF ){
printf( "%d\n", searchh(root,getss) );
}
return 0;
}