字典树题目,上题,输入字典,输入字符串,给出对应字符串为前缀的数量,
banana band bee absolute acm ba b band abc
2 3 1 0
直接字典树,然后每个都统计一次size,每添加/经过一个结点都size++
#include<stdio.h> #include<string.h> #include<iostream> struct node { int size; node *ch[26]; node() { size = 0; for(int i = 0 ; i < 26 ; i++) { ch[i] = NULL; } } }; /de *root = new node; node root[100005]; node *current,*newnode; void INSERT(char *s) { int len = strlen(s); int i,m; current = root; for(i = 0 ; i < len ;i++) { m = s[i]-'a'; if(current->ch[m]!=NULL) { current = current->ch[m]; (current->size)++; } else { newnode = new node; (newnode->size)++; current->ch[m] = newnode; current = newnode; } } } int QUERY(char *s) { int i,m; current = root; for(i = 0 ; i < strlen(s);i++) { m = s[i]-'a'; if(current->ch[m]==NULL) return 0; current = current->ch[m]; } return current->size; } using namespace std; int main() { char str[20]; while(gets(str),strcmp(str,"")) { INSERT(str); } while(gets(str)!=NULL) { printf("%d\n",QUERY(str)); } delete [] newnode; newnode = NULL; return 0; }