fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. class TrieNode{
  5. public:
  6. int fr[26];
  7. int endHere;
  8. TrieNode* children[26];
  9.  
  10. TrieNode() {
  11. endHere = 0;
  12. for(int i = 0;i<26;i++){
  13. children[i] = NULL;
  14. fr[i] = 0;
  15. }
  16. }
  17. };
  18.  
  19. class Trie {
  20. public:
  21. TrieNode* root;
  22.  
  23. Trie() {
  24. root = new TrieNode();
  25. }
  26.  
  27. int insert(string word) {
  28. TrieNode* curr = root;
  29. int hits = 0, hit=0;
  30. for(int i = 0; i<word.size(); i++) {
  31. int index = word[i] - 'a';
  32. if(curr->children[index] == NULL) {
  33. curr->children[index] = new TrieNode();
  34. }
  35. curr = curr->children[index];
  36. hit += curr->endHere;
  37. hits = curr->fr[index];
  38. (curr->fr[index])++;
  39. }
  40. hit -= curr->endHere;
  41. (curr->endHere)++;
  42. return hits+hit;
  43. }
  44. };
  45.  
  46.  
  47. void solve(vector<string> v) {
  48. int n = v.size();
  49. int ans = 0;
  50. Trie t;
  51. for(int i=0;i<n;i++) {
  52. int val = t.insert(v[i]);
  53. ans += val;
  54. }
  55. cout << ans << endl;
  56. }
  57.  
  58. int main() {
  59. solve({"wall", "wallpaper", "science", "wallet", "philosopher", "phil", "book"});
  60. solve({"abc","a","a","b","ab","ac"});
  61. solve({"a", "a", "a", "a", "abc"});
  62. return 0;
  63. }
Success #stdin #stdout 0.01s 5276KB
stdin
Standard input is empty
stdout
3
8
10