Advertisement
Guest User

Type printer

a guest
Aug 21st, 2014
244
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.80 KB | None | 0 0
  1. #include <iostream>
  2. #include <fstream>
  3. #include <vector>
  4. #include <string>
  5. #include <algorithm>
  6.  
  7. using namespace std;
  8.  
  9. int contaOp = 0;
  10.  
  11. struct trie
  12. {
  13.     bool print;
  14.     char c;
  15.     vector<trie> sons;
  16.     int mWord;
  17. };
  18.  
  19. bool operator<(const trie &a, const trie&b)
  20. {
  21.     return a.mWord < b.mWord;
  22. }
  23.  
  24. void addWord(string w, trie &node)
  25. {
  26.     if(w.empty())
  27.     {
  28.         node.print = true;
  29.         return;
  30.     }
  31.  
  32.     bool found = false;
  33.     int i = 0;
  34.     for(i = 0; i < (int)node.sons.size() && !found; i++)
  35.     if(node.sons[i].c == w[0]) found = true;
  36.  
  37.     if(!found)
  38.     {
  39.         trie newNode;
  40.         newNode.c = w[0];
  41.         newNode.mWord = 0;
  42.         newNode.print = false;
  43.         node.sons.push_back(newNode);
  44.     }
  45.     else i--;
  46.  
  47.     node.sons[i].mWord = max(node.sons[i].mWord, (int)w.length());
  48.  
  49.     addWord(w.substr(1, string::npos), node.sons[i]);
  50. }
  51.  
  52. void printSol(int &N, trie &nodo, ofstream &out)
  53. {
  54.     if(nodo.print)
  55.     {
  56.     N--;
  57.     out << "P\n";
  58.     contaOp++;
  59.     }
  60.  
  61.     if(nodo.sons.empty())
  62.     return;
  63.  
  64.     nth_element(nodo.sons.begin(), nodo.sons.end()-1, nodo.sons.end());
  65.  
  66.     int i = 0;
  67.  
  68.     while(i < nodo.sons.size())
  69.     {
  70.         out << nodo.sons[i].c << "\n";
  71.         contaOp++;
  72.         printSol(N, nodo.sons[i], out);
  73.         if(N > 0) { out << "-\n"; contaOp++; }
  74.         i++;
  75.     }
  76. }
  77.  
  78.  
  79. int main()
  80. {
  81.     ifstream in("input.txt");
  82.     ofstream out("output.txt");
  83.  
  84.     int N;
  85.     string w;
  86.     trie triet;
  87.     triet.c = '0';
  88.     triet.print = false;
  89.     in >> N;
  90.  
  91.     for(int i = 0; i < N; i++)
  92.     {
  93.         in >> w;
  94.         addWord(w, triet);
  95.     }
  96.  
  97.     out << "                                             \n";
  98.  
  99.     printSol(N, triet, out);
  100.  
  101.     out.seekp(ios_base::beg);
  102.  
  103.     out << contaOp;
  104.  
  105.  
  106.  
  107.     return 0;
  108. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement