Trie 字典树(c++)(前缀)
原创 已于 2024-01-29 14:47:28 修改 · 粉丝可见 · 486 阅读 · 9 · 10 · 本内容遵循CC 4.0 BY-SA版权协议 版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。 GEO检测 · 编辑
文章链接:https://blog.csdn.net/hacker_51/article/details/135070623
题目链接: 用户登录
题目:

样例:
cobol<br/>5 3<br/>aaa<br/>aba<br/>aabbaa<br/>abbbbb<br/>cdd<br/>aabba<br/>abc<br/>abab<br/> |
undefined<br/>Y<br/>N<br/>N<br/> |

思路:
根据题目意思,要用到 Trie 字典树算法。
Trie 字典树,顾名思义,“字典”,我们查字典的时候,都是找开头的几个字符,来获取我们的整个字符,Trie 字典树,就是通过 前缀字符的一步步扩展。最后查找的时候就是根据我们扩展字典树的步骤来变相查找。字典树,我们也要建立一个 root 根
比如 :给出以下的几个字符
abcdf
bgre
abfr
baef
最后获得的字典树为:

下面给出 Trie 字典树封装的结构体:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
|
struct Tries { int son[N][26],idx; inline Tries() { memset(son,0,sizeof son); idx = 0; } inline void Insert(string str) { int p = 0; int len = str.size(); for(int i = 0;i < len;++i) { int u = str[i] - 'a'; if(!son[p][u]) son[p][u] = ++idx; p = son[p][u]; } return ; } inline bool query(string str) { int p = 0; int len = str.size(); for(int i = 0;i < len;++i) { int u = str[i] - 'a'; if(!son[p][u]) return false; p = son[p][u]; } return true; } }tree;
|
代码详解如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
| #include <iostream> #include <vector> #include <queue> #include <cstring> #include <algorithm> #include <unordered_map> #define endl '\n' #define int long long #define YES puts("YES") #define NO puts("NO") #define umap unordered_map #define All(x) x.begin(),x.end() #pragma GCC optimize(3,"Ofast","inline") #define IOS std::ios::sync_with_stdio(false),cin.tie(0), cout.tie(0) using namespace std; const int N = 2e5 + 10;
struct Tries { int son[N][26],idx; inline Tries() { memset(son,0,sizeof son); idx = 0; } inline void Insert(string str) { int p = 0; int len = str.size(); for(int i = 0;i < len;++i) { int u = str[i] - 'a'; if(!son[p][u]) son[p][u] = ++idx; p = son[p][u]; } return ; } inline bool query(string str) { int p = 0; int len = str.size(); for(int i = 0;i < len;++i) { int u = str[i] - 'a'; if(!son[p][u]) return false; p = son[p][u]; } return true; } }tree; int n,k; string s; inline void solve() { cin >> n >> k; while(n--) { cin >> s; tree.Insert(s); } while(k--) { cin >> s; if(tree.query(s)) cout << "Y" << endl; else cout << "N" << endl; } } signed main() {
IOS; int _t = 1;
while (_t--) { solve(); } return 0; }
|
最后提交:
