Advertisement
newb_ie

trie

Aug 2nd, 2021
225
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.37 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3.  
  4. const int k = 26;
  5.  
  6. struct Vertex {
  7. int next[k];
  8. bool leaf = false;
  9. Vertex() {
  10. fill(next,next + k,-1);
  11. }
  12. };
  13.  
  14. vector<Vertex> trie(1);
  15.  
  16. void insert (string const& s) {
  17. int v = 0;
  18. for (int i = 0; i < (int) s.size(); ++i) {
  19. if (trie[v].next[s[i] - '0'] == -1) {
  20. trie[v].next[s[i] - '0'] = trie.size();
  21. trie.emplace_back();
  22. }
  23. v = trie[v].next[s[i] - '0'];
  24. }
  25. trie[v].leaf = true;
  26. }
  27.  
  28.  
  29. bool find (string const& s) {
  30. int v = 0;
  31. for (int i = 0; i < (int) s.size(); ++i) {
  32. if (trie[v].next[s[i] - '0'] == -1) return false;
  33. v = trie[v].next[s[i] - '0'];
  34. if ((int) s.size() == i + 1 and trie[v].leaf) return false;
  35. }
  36. return true;
  37. }
  38.  
  39. int main () {
  40. ios::sync_with_stdio(false);
  41. cin.tie(nullptr);
  42. cout.tie(nullptr);
  43. int T;
  44. cin >> T;
  45. for (int test_case = 1; test_case <= T; ++test_case) {
  46. int n;
  47. cin >> n;
  48. vector<pair<int,string>> s;
  49. for (int i = 0; i < n; ++i) {
  50. string in;
  51. cin >> in;
  52. s.push_back(make_pair((int) in.size(),in));
  53. }
  54. sort (s.rbegin(),s.rend());
  55. bool yes = true;
  56. for (int i = 0; i < (int) s.size(); ++i) {
  57. if (find(s[i].second)) {
  58. yes = false;
  59. break;
  60. }
  61. insert(s[i].second);
  62. }
  63. cout << (yes ? "YES\n" : "NO\n");
  64. }
  65. //cerr << "Time elapsed :" << clock() * 1000.0 / CLOCKS_PER_SEC << " ms" << '\n';
  66. }
  67.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement