Advertisement
Guest User

Untitled

a guest
Jul 17th, 2018
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.89 KB | None | 0 0
  1. #include <iostream>
  2. #include <map>
  3. #include <set>
  4. #include <vector>
  5. #include <algorithm>
  6.  
  7. enum Mark {
  8.     Unmarked,
  9.     Permanent,
  10.     Temporary
  11. };
  12.  
  13. void dfs(char current,
  14.     std::map<char, std::set<char>> &graph,
  15.     std::map <char, Mark> &marks,
  16.     std::vector <char> &path,
  17.     bool &has_cycle) {
  18.  
  19.     if (marks[current] == Permanent) {
  20.         return;
  21.     }
  22.  
  23.     if (marks[current] == Temporary)
  24.     {
  25.         has_cycle = true;
  26.         return;
  27.     }
  28.  
  29.     marks[current] = Temporary;
  30.  
  31.     for (const auto& v : graph[current]) {
  32.         dfs(v, graph, marks, path, has_cycle);
  33.     }
  34.  
  35.     marks[current] = Permanent;
  36.  
  37.     path.push_back(current);
  38. }
  39.  
  40. bool top_sort(std::map <char, std::set<char>> &graph, std::vector <char> &alphabet) {
  41.     std::map <char, Mark> marks;
  42.     bool has_cycle = false;
  43.  
  44.     for (auto& v : graph) {
  45.         if (marks[v.first] == Unmarked) {
  46.             dfs(v.first, graph, marks, alphabet, has_cycle);
  47.         }
  48.     }
  49.  
  50.     std::reverse(alphabet.begin(), alphabet.end());
  51.     return has_cycle;
  52. }
  53.  
  54.  
  55. std::map<char, std::set<char>> build_graph(const std::vector<std::string>& dictionary) {
  56.     std::map<char, std::set<char>> graph;
  57.  
  58.     for (size_t i = 0; i < dictionary.size(); ++i) {
  59.         for (size_t j = i + 1; j < dictionary.size(); ++j) {
  60.            
  61.             size_t length = std::min(dictionary[i].size(), dictionary[j].size());
  62.            
  63.             for (size_t k = 0; k < length; ++k) {
  64.                 if (dictionary[i][k] != dictionary[j][k]) {
  65.                     graph[dictionary[i][k]].insert(dictionary[j][k]);
  66.                     break;
  67.                 }
  68.             }
  69.         }
  70.     }
  71.  
  72.     return graph;
  73. }
  74.  
  75. void print_alphabet(std::vector<std::string> dictionary) {
  76.     auto graph = build_graph(dictionary);
  77.  
  78.     std::vector <char> alphabet;
  79.     bool has_cycle = top_sort(graph, alphabet);
  80.  
  81.     if (!has_cycle) {
  82.         for (auto ch : alphabet)
  83.             std::cout << ch << ' ';
  84.     }
  85.     else {
  86.         std::cout << "No alphabet possible";
  87.     }
  88. }
  89.  
  90.  
  91. int main() {
  92.     std::vector<std::string> dictionary = { "ART", "RAT", "CAT", "CAR" };
  93.     print_alphabet(dictionary);
  94. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement