在hdu上要用c++提交,要不然会超内存。
传送门:http://acm.hdu.edu.cn/showproblem.php?pid=1251
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define maxn 30
struct Trie{
Trie * next[maxn];
int v;
};
Trie * root;
void Init_Trie(){
root = (Trie *)malloc(sizeof(Trie));
for(int i=0;i<maxn;i++){
root -> next[i] = NULL;
}
}
void Add_Trie(char * str){
Trie * p = root , * q;
for(int i=0;str[i]!='\0';i++){
int id = str[i] - 'a';
if(p->next[id]==NULL){
q = (Trie *)malloc(sizeof(Trie));
q -> v = 1;
for(int j=0;j<maxn;j++){
q -> next[j] = NULL;
}
p -> next[id] = q;
p = p -> next[id];
}
else {
p -> next[id]->v++;
p = p -> next[id];
}
}
//p -> v ++;
}
int Search_Trie(char * str){
Trie * p = root;
for(int i=0;str[i]!='\0';i++){
int id = str[i] - 'a';
p = p -> next[id];
if(p==NULL){
return 0;
}
}
return p -> v;
}
void Del_Trie(Trie * p){
for(int i=0;i<maxn;i++){
if(p->next[i])Del_Trie(p->next[i]);
}
free(p);
}
void input(){
char a[15];
Init_Trie();
while(gets(a),a[0]!='\0'){
Add_Trie(a);
}
while(~scanf("%s",a)){
printf("%d\n",Search_Trie(a));
}
Del_Trie(root);
}
void File(){
freopen("a.in","r",stdin);
freopen("a.out","w",stdout);
}
int main(void){
//File();
input();
return 0;
}