int trie[400100][26]; int sum[400100]; int pos=1; void insert1(char *s) { int root=0; for(int i=0;i<strlen(s);i++) { int ch=s[i]-'a'; if( trie[ root ][ch]==0 ) { memset(trie[pos],0,sizeof(trie[pos]));//用多少初始化多少 trie[root][ch]=pos++; } root=trie[root][ch]; } sum[root]=1; } int find1(char *s) { int root=0; for(int i=0;i<strlen(s);i++) { int ch=s[i]-'a'; if( trie[root][ch]==0 )return false; root=trie[root][ch]; } return sum[root]; } int main() { pos=1; memset(sum,0,sizeof(sum)); memset(trie[0],0,sizeof(trie[0])); return 0; }
指针写法
#include<cstdio> #include<cstring> #include<iostream> #include<algorithm> using namespace std; char s[11]; int n,m; bool p; struct node { int count; node * next[26]; }*root; node * build() { node * k=new(node); k->count=0; memset(k->next,0,sizeof(k->next)); return k; } void insert() { node * r=root; char * word=s; while(*word) { int id=*word-'a'; if(r->next[id]==NULL) r->next[id]=build(); r=r->next[id]; r->count++; word++; } } int search() { node * r=root; char * word=s; while(*word) { int id=*word-'a'; r=r->next[id]; if(r==NULL) return 0; word++; } return r->count; } int main() { root=build(); scanf("%d",&n); for(int i=1;i<=n;i++) { cin>>s; insert(); } scanf("%d",&m); for(int i=1;i<=m;i++) { cin>>s; printf("%d\n",search()); } }