HDU-5687 Problem C (字典树)插入,查找,删除
1 #include <iostream> 2 #include <algorithm> 3 #include <cstring> 4 #include <string> 5 #include <vector> 6 7 using namespace std; 8 typedef long long ll; 9 10 const int maxn = 1300005; 11 int pos = 1; 12 13 int trie[maxn][26]; 14 int num[maxn]; 15 16 void insert(string str) 17 { 18 int p = 0; 19 for (int i = 0; str[i]; i++) 20 { 21 int n = str[i] - 'a'; 22 if (!trie[p][n]) 23 { 24 trie[p][n] = pos++; 25 } 26 p = trie[p][n]; 27 num[p]++; 28 } 29 } 30 31 int Find(string str) 32 { 33 int p = 0; 34 for (int i = 0; str[i]; i++) 35 { 36 int n = str[i] - 'a'; 37 if (!trie[p][n]) 38 return 0; 39 p = trie[p][n]; 40 } 41 return num[p]; 42 } 43 44 void Delete(string str) 45 { 46 int p = 0; 47 for (int i = 0; str[i]; i++) 48 { 49 int n = str[i] - 'a'; 50 if (!trie[p][n]) return; 51 p = trie[p][n]; 52 } 53 int cnt = num[p]; 54 // 先跑一遍,看有没有这个string。 55 p = 0; 56 for (int i = 0; str[i]; i++) 57 { 58 int n = str[i] - 'a'; 59 p = trie[p][n]; 60 num[p] -= cnt; 61 } 62 for (int i = 0; i < 26; i++) 63 { 64 trie[p][i] = 0; 65 } 66 } 67 68 int main() 69 { 70 int t; 71 cin >> t; 72 string c, s; 73 while (t--) 74 { 75 cin >> c >> s; 76 if (c == "insert") insert(s); 77 else if (c == "search") 78 { 79 if (Find(s)) cout << "Yes" << endl; 80 else cout << "No" << endl; 81 } 82 else Delete(s); 83 } 84 return 0; 85 }