fork download
  1. /**
  2.  * Trie - a tree for keeping a set of words, factoring out duplicate prefixes.
  3.  * Demo application - keep a sorted set of words.
  4.  *
  5.  * INPUT: a list of words.
  6.  * OUTPUT: the same list, sorted and without duplicates.
  7.  *
  8.  * Author: Erel Segal
  9.  * Created: 2010-10-14
  10.  */
  11.  
  12. #include <map>
  13. #include <string>
  14. #include <iostream>
  15. using namespace std;
  16.  
  17.  
  18. class Trie;
  19. typedef Trie* PTrieNode;
  20.  
  21. class Trie {
  22. map<char,PTrieNode> myChildren;
  23. bool isWordEnd; // "true" if a word ends in this node
  24.  
  25. public:
  26.  
  27. Trie(): isWordEnd(false) {}
  28.  
  29. /* recursively add a single word to the node */
  30. void add (const char* newWord) {
  31. char first = newWord[0];
  32. if (!first) { // empty word
  33. isWordEnd = true;
  34. } else {
  35. if (!myChildren[first]) {
  36. myChildren[first] = new Trie();
  37. }
  38. myChildren[first]->add(newWord+1);
  39. }
  40. }
  41.  
  42. /* recursively print all words in the node in order */
  43. void print (ostream& out, string prefix) const {
  44. if (isWordEnd) {
  45. out << prefix << " ";
  46. }
  47.  
  48. map<char,PTrieNode>::const_iterator it;
  49. for (it=myChildren.begin() ; it!=myChildren.end(); it++) {
  50. char c = (*it).first;
  51. PTrieNode child = (*it).second;
  52. child->print(out, prefix+c);
  53. }
  54. }
  55.  
  56. friend ostream& operator<< (ostream& out, const Trie& node) {
  57. node.print(out, /*prefix=*/"");
  58. return out;
  59. }
  60. };
  61.  
  62.  
  63.  
  64. int main() {
  65. Trie t;
  66. string word;
  67. while (!cin.eof()) {
  68. cin >> word;
  69. t.add(word.c_str());
  70. cout << t << endl;
  71. }
  72. }
  73.  
  74.  
  75.  
Success #stdin #stdout 0s 2868KB
stdin
abc
ab
a
c
cb
cba
bca
bc
b
a
ab
abc
stdout
abc 
ab abc 
a ab abc 
a ab abc c 
a ab abc c cb 
a ab abc c cb cba 
a ab abc bca c cb cba 
a ab abc bc bca c cb cba 
a ab abc b bc bca c cb cba 
a ab abc b bc bca c cb cba 
a ab abc b bc bca c cb cba 
a ab abc b bc bca c cb cba 
a ab abc b bc bca c cb cba