HDU 1251 字典树(前缀树)

时间:2022-04-15 05:03:14

题目大意 :Ignatius最近遇到一个难题,老师交给他很多单词(只有小写字母组成,不会有重复的单词出现),现在老师要他统计出以某个字符串为前缀的单词数量(单词本身也是自己的前缀).(单词互不相同)

代码:

  #include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<queue>
#include<algorithm>
#include<cmath>
#include<map>
using namespace std;
#define INF 0x7fffffff int ch[1000000][30],isword[1000000];
int num[1000000],nz; void insert(char s[],int len){
int i,j,u = 0;
num[u]++;
for(i=0;i<len;i++){
int v = s[i] - 'a' ;
if(!ch[u][v]){
memset(ch[nz],0,sizeof(ch[nz]));
isword[nz] = 0;
ch[u][v] = nz ++ ;
}
u = ch[u][v] ;
num[u]++;
}
isword[u] = 1;
} int query(char s[]){
int i,j,len,u = 0;
len = strlen(s);
for(i=0;i<len;i++){
int v = s[i] - 'a';
if(!ch[u][v]){
return 0;
}
u = ch[u][v];
}
return num[u];
} int main(){
int i,len;
char s[12],c;
nz = 1;
memset(num,0,sizeof(num));
memset(ch[0],0,sizeof(ch[0]));
c = getchar();
while(c != '\n'){
gets(s+1);
s[0] = c ;
len = strlen(s);
s[len] = '\0' ;
insert(s,len);
c = getchar();
} while(scanf("%s",s) == 1){
int ans = query(s);
printf("%d\n",ans);
}
return 0;
}