思路:一道裸的字典树题。先存代码以后备用。
代码如下:
1 /************************************************** 2 * Author : xiaohao Z 3 * Blog : http://www.cnblogs.com/shu-xiaohao/ 4 * Last modified : 2014-04-07 13:10 5 * Filename : testTrie.cpp 6 * Description : 7 * ************************************************/ 8 9 #include <iostream> 10 #include <cstdio> 11 #include <cstring> 12 #include <cstdlib> 13 #include <cmath> 14 #include <algorithm> 15 #include <queue> 16 #include <stack> 17 #include <vector> 18 #include <set> 19 #include <map> 20 #define MP(a, b) make_pair(a, b) 21 #define PB(a) push_back(a) 22 23 using namespace std; 24 typedef long long ll; 25 typedef pair<int, int> pii; 26 typedef pair<unsigned int,unsigned int> puu; 27 typedef pair<int, double> pid; 28 typedef pair<ll, int> pli; 29 typedef pair<int, ll> pil; 30 31 const int INF = 0x3f3f3f3f; 32 const double eps = 1E-6; 33 const int LEN = 1010; 34 35 struct Node{ 36 int data, num; 37 bool flag; 38 Node *ch[26]; 39 Node(){ 40 memset(ch, 0, sizeof ch); 41 flag = num = 0; 42 data = -1; 43 } 44 }; 45 46 class Trie{ 47 Node* head; 48 int getpos(char c){return c-'a';} 49 public: 50 Trie(){head = new Node;} 51 void insert(string s, int _data){ 52 Node* p = head; 53 for(int i=0; i<s.size(); i++){ 54 if(!p->ch[getpos(s[i])]){ 55 p->ch[getpos(s[i])] = new Node; 56 } 57 p->num ++; 58 p = p->ch[getpos(s[i])]; 59 } 60 p->num ++; 61 p->data = _data; 62 p->flag = 1; 63 } 64 65 bool query(string s, int &_data, int &cnt){ 66 Node* p = head; 67 for(int i=0; i<s.size(); i++){ 68 if(!p->ch[getpos(s[i])]) return false; 69 p = p->ch[getpos(s[i])]; 70 } 71 cnt = p->num; 72 if(p->flag){ 73 _data = p->data; 74 return true; 75 } 76 return false; 77 } 78 }; 79 80 int main() 81 { 82 // freopen("in.txt", "r", stdin); 83 84 char str[110]; 85 Trie T; 86 while(gets(str)){ 87 if(strlen(str) == 0) break; 88 T.insert(str, 1); 89 } 90 int data; 91 while(cin >> str){ 92 int cnt = 0; 93 T.query(str, data, cnt); 94 cout << cnt << endl; 95 } 96 return 0; 97 }