Poj--3193(字典树)
2014-12-07 01:12:32
思路:嘛,一开始懒不想敲trie,想直接用set 哈希最多 60 × 1000个前缀....感觉效率貌似够,结果果断T了。
无奈,复习下Trie吧,这道就是经典的存字典型Trie,具体见代码吧。(单组case,没写delete_trie)
1 /************************************************************************* 2 > File Name: 3193.cpp 3 > Author: Nature 4 > Mail: 564374850@qq.com 5 > Created Time: Sat 06 Dec 2014 05:05:31 PM CST 6 ************************************************************************/ 7 8 #include <cstdio> 9 #include <cstring> 10 #include <cstdlib> 11 #include <cmath> 12 #include <vector> 13 #include <map> 14 #include <set> 15 #include <stack> 16 #include <queue> 17 #include <iostream> 18 #include <algorithm> 19 using namespace std; 20 #define lp (p << 1) 21 #define rp (p << 1|1) 22 #define getmid(l,r) (l + (r - l) / 2) 23 #define MP(a,b) make_pair(a,b) 24 typedef long long ll; 25 const int INF = 1 << 30; 26 27 int M,N; 28 char book[100000]; 29 30 struct Trie{ 31 Trie *next[130]; 32 }*root; 33 34 void Insert_tree(char *str){ 35 int len = strlen(str); 36 Trie *p = root,*q; 37 for(int i = 0; i < len; ++i){ 38 int id = str[i]; 39 if(p->next[id] == NULL){ 40 q = (Trie *)malloc(sizeof(Trie)); 41 for(int i = 0; i < 130; ++i) q->next[i] = NULL; 42 p->next[id] = q; 43 } 44 p = p->next[id]; 45 } 46 } 47 48 bool Find(){ 49 Trie *p = root; 50 char c = getchar(); 51 bool flag = true; 52 while(c != '\n'){ 53 int id = c; 54 c = getchar(); 55 if(!flag) continue; 56 if(p->next[id] == NULL) flag = false; 57 p = p->next[id]; 58 } 59 return flag; 60 } 61 62 int main(){ 63 root = (Trie *)malloc(sizeof(Trie)); 64 for(int i = 0; i < 130; ++i) root->next[i] = NULL; 65 scanf("%d%d",&M,&N); 66 getchar(); 67 for(int i = 1; i <= M; ++i){ 68 gets(book); 69 Insert_tree(book); 70 } 71 int ans = 0; 72 for(int i = 1; i <= N; ++i){ 73 if(Find()) 74 ++ans; 75 } 76 printf("%d\n",ans); 77 return 0; 78 }