bananabandbeeabsoluteacmbabbandabc Sample Output2310解题报告:字典树模板题,注意提交时用C++编译器,G++会超时。
code:
#include<iostream>#include<stdio.h>#include<queue>#include<vector>#include<stack>#include<cstring>#include<algorithm>using namespace std;typedef long long ll;const int maxn=100005;const int MAX=26;typedef struct node{ struct node *next[MAX]; int flag; //该字母出现的次数}Trie;Trie *root;/*root要初始化root=(Trie *)malloc(sizeof(Trie));root->flag=0;for(int i=0;i<MAX;i++){ root->next[i]=NULL;}*/void createTrie(char *str) //创建一棵字典树{ int len = strlen(str); Trie *p = root, *q; for(int i=0; i<len; i++) { int id = str[i]-'a'; //小写字母 if(p->next[id] == NULL) { q = (Trie *)malloc(sizeof(Trie)); q->flag = 0; for(int j=0; j<MAX; j++) q->next[j] = NULL; p->next[id] = q; } p = p->next[id]; p->flag++; }}int findTrie(char *str) //找出以str字符串为前缀的单词的数量.{ int len = strlen(str); Trie *p = root; for(int i=0; i<len; i++) { int id = str[i]-'a'; p = p->next[id]; if(p == NULL) //若为空集,表示不存以此为前缀的串 return 0; } return p->flag;}int main(){ // freopen("input.txt","r",stdin); root=(Trie *)malloc(sizeof(Trie)); //初始化 root->flag=0; for(int i=0;i<MAX;i++){ root->next[i]=NULL; } char s[15]; while(gets(s)){ if(strlen(s)==0) break; createTrie(s); } while(~scanf("%s",s)){ printf("%d/n",findTrie(s)); } return 0;}
新闻热点
疑难解答