Original title Link: http://acm.hdu.edu.cn/showproblem.php?pid=1251
Main algorithm:
The problem uses the knowledge of the dictionary tree. When you enter a word, create a dictionary tree. The value of V for each node represents the number of occurrences of the prefix from the root node to all letters on that node's path. When entering a prefix, simply look for the prefix in the dictionary tree, and if so, the value of V of the last letter of the output prefix, if none, Output 0.
AC Code:
# include<stdio.h> # include<string.h> # include<malloc.h> # define MAX typedef struct trie{str
UCT Trie *next[max];
int v;//records the number of occurrences of the prefix of the last letter of the node}trie;
Trie * ROOT=NULL;
void Inserttrie (char words[]);
void Createtrie ();
int search (char perfix[]);
int main () {Createtrie ();
Char perfix[10];
while (scanf ("%s", Perfix)!=eof) {printf ("%d\n", Search (Perfix));
} return 0;
}//Build the Dictionary tree void Createtrie () {int i;
Char words[12];
if (!root) root= (Trie *) malloc (sizeof (Trie));
for (i=0;i<max;i++) root->next[i]=null;
root->v=0;
The while (gets (words) &&strcmp (words, "//gets")!=0) the () function reads the entire row of data and converts ' \ n ' to ' + ' {inserttrie (words);
}}//insert Word into the dictionary tree void Inserttrie (char words[]) {Trie *p=root;
int Len=strlen (words), i,j;
for (i=0;i<len;i++) {int id=words[i]-' a '; if (p->next[id]==null)//node of ' a ' +id not present on the layer, new, and v=1 {P->next[id]= (Trie *) malloc (sizeof (Trie));
p=p->next[id];
p->v=1;
for (j=0;j<max;j++) p->next[j]=null;
} else {p=p->next[id];
(p->v) + +;
}}}//query in the dictionary tree if there is a prefix int search (char perfix[]) {Trie *p=root;
int Len=strlen (perfix), I;
for (i=0;i<len;i++) {int id=perfix[i]-' a ';
if (p->next[id]==null) break;
p=p->next[id];
} if (I<len) return 0;
else return p->v; }