注意数组大小,字典树比较浪费空间,在统计个数时,不要再结构体中再开26的数组
还有下面更新与统计时,注意与指针pre的先后顺序
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxn = 500000;
struct node{
int next[26], cnt;
void ini(){
memset( next, -1, sizeof( next));
cnt = 0; //这里注意,记录不要开成cnt[26]
}
}tree[maxn];
int main(){
//freopen("1.txt", "r", stdin);
char tmp[20];
int flag = 0;
int ans, i, j, k, pre = 0, len, aa;
ans = 1;
for( i= 0; i<maxn; i++) tree[i].ini();
while( gets(tmp)){
len = strlen( tmp);
if( len == 0 ) flag = 1;
if( flag == 0){
pre = 0;
for( i= 0; i<len; i++){
aa = tmp[i]- 'a';
if( tree[pre].next[aa] == -1){
tree[pre].next[aa] = ans;
pre = ans;
ans++;
}
else {
pre = tree[pre].next[aa];
}
tree[pre].cnt ++;
}
}
else{
pre= 0;
for( i= 0; i<len; i++){
aa = tmp[i]- 'a';
if( tree[pre].next[aa] == -1){
printf("0\n");
break;
}
else {
pre = tree[pre].next[aa];
if( i== (len - 1)){
printf("%d\n", tree[pre].cnt);
}
}
}
}
}
return 0;
}