trie树
#include <cstdio> #include <cstring> #include <vector> #include <string> #include <iostream> #include <algorithm> #include <map> using namespace std; const int N = 100010; struct Tree { int v; struct Tree *pchild[26]; Tree():v(1) { for(int i=0;i<26;i++) pchild[i]=NULL; } }*tree; void build(Tree *tree,char *s) { tree->v++; int len = strlen(s); for(int i = 0; i < len; i++) { int u = s[i]-'a'; if(tree->pchild[u] == NULL) { Tree *p = new Tree; tree->pchild[u] = p; } else { tree->pchild[u]->v++; } tree = tree->pchild[u]; } } int find(Tree *tree,char *s) { int len = strlen(s); for(int i = 0; i < len; i++) { int u = s[i]-'a'; if(tree->pchild[u] == NULL) return 0; if(i+1 == len) return tree->pchild[u]->v; tree = tree->pchild[u]; } } int main() { int n,m; tree = new Tree(); tree->v = 0; scanf("%d",&n); char a[50]; for(int i = 0; i < n; i ++) { scanf("%s",a); build(tree,a); } scanf("%d",&m); for(int i = 0; i < m; i ++) { scanf("%s",a); printf("%d\n",find(tree,a)); } return 0; }
posted on 2015-11-20 15:42 zyz913614263 阅读(155) 评论(0) 编辑 收藏 举报