P2580 于是他错误的点名开始了(Trie)
https://www.luogu.com.cn/problem/P2580
#include <bits/stdc++.h> using namespace std; const int maxn = 5e5 + 5; int n,m; string s; int num; struct node{ int son[27],cnt; bool flag; }trie[maxn]; void insert(string s){ int u = 0; for(int i = 0; i < s.size(); i++){ int v = s[i] - 'a'; if(!trie[u].son[v]) trie[u].son[v] = ++num; u = trie[u].son[v]; } trie[u].flag = true; } int find(string s){ int u = 0; for(int i = 0; i < s.size(); i++){ int v = s[i] - 'a'; if(!trie[u].son[v]) return 3; u = trie[u].son[v]; } if(!trie[u].flag) return 3; if(!trie[u].cnt){ trie[u].cnt++; return 1; } return 2; } int main(){ //freopen("in","r",stdin); ios::sync_with_stdio(0); cin >> n; for(int i = 0; i < n; i++){ cin >> s; insert(s); } cin >> m; for(int i = 0; i < m; i++) { cin >> s; if(find(s) == 1) cout << "OK\n"; else if(find(s) == 2) cout << "REPEAT\n"; else cout << "WRONG\n"; } return 0; }
UVA11362 Phone List
https://www.luogu.com.cn/problem/UVA11362
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#include<bits/stdc++.h> using namespace std; const int maxn = 4e5 + 5; struct node { int son[11], sum; bool flag; void clear() { memset(son, 0, sizeof(son)); sum = 0; flag = 0; } } trie[maxn]; int n, t, num; string s[maxn]; void insert(string s) { int len = s.size(), u = 0; for (int i = 0; i < len; i++) { int v = s[i] - '0'; if (!trie[u].son[v]) trie[u].son[v] = ++num; trie[u].sum++; u = trie[u].son[v]; } trie[u].flag = true; } int find(string s) { int len = s.size(), u = 0; for (int i = 0; i < len; i++) { int v = s[i] - '0'; if (!trie[u].son[v]) return 0; u = trie[u].son[v]; } if (trie[u].sum == 0)return 0; return 1; } int main() { //freopen("in", "r", stdin); cin >> t; while (t--) { num = 0; for (int i = 0; i < maxn; i++) trie[i].clear(); cin >> n; for (int i = 0; i < n; i++) { cin >> s[i]; insert(s[i]); } bool ans = false; for (int i = 0; i < n; i++) { int res = find(s[i]); if (res == 1) { ans = true; break; } } if (ans) cout << "NO\n"; else cout << "YES\n"; } }
大佬的博客
https://www.luogu.com.cn/blog/juruohyfhaha/trie-xue-xi-zong-jie