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;}
新聞熱點
疑難解答