vlad7576

up08-3 (grammar 1)

May 17th, 2020
80
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 <string>
  4. #include <algorithm>
  5. #include <cctype>
  6.  
  7. std::string to_lower(const std::string &s)
  8. {
  9.     std::string data(s);
  10.     std::transform(data.begin(), data.end(), data.begin(), [](unsigned char c) { return std::tolower(c); });
  11.     return data;
  12. }
  13.  
  14.  
  15. bool is_grammar(const std::multimap<std::string, std::string> &dict)
  16. {
  17.     if (dict.empty() || dict.count(std::string("S")) == 0) {
  18.         return false;
  19.     }
  20.     for (auto &c:dict) {
  21.         if (c.first == to_lower(c.first)) {
  22.             return false;
  23.         }
  24.     }
  25.     return true;
  26. }
  27.  
  28. bool is_context_free(const std::multimap<std::string, std::string> &dict)
  29. {
  30.     for (auto &c:dict) {
  31.         if (c.first.size() != 1 || c.first[0] != std::toupper(c.first[0])) {
  32.             return false;
  33.         }
  34.     }
  35.     return true;
  36. }
  37.  
  38. bool is_inconclusive_context_free(const std::multimap<std::string, std::string> &dict)
  39. {
  40.     bool flag1 = false;
  41.     bool flag2 = false;
  42.     if (!is_context_free(dict)) {
  43.         return false;
  44.     }
  45.     for (auto &c:dict) {
  46.         if (c.second.find("S") != std::string::npos) {
  47.             flag1 = true;
  48.         }
  49.         if (c.second == "_") {
  50.             if (c.first != "S") {
  51.                 return false;
  52.             } else {
  53.                 flag2 = true;
  54.             }
  55.         }
  56.     }
  57.     return !(flag1 && flag2);
  58. }
  59.  
  60. int main()
  61. {
  62.     std::multimap<std::string, std::string> dict;
  63.     std::string key, value;
  64.     while (std::cin >> key >> value) {
  65.         dict.insert({key, value});
  66.     }
  67.     if (!is_grammar(dict)) {
  68.         std::cout << "-1" << std::endl;
  69.     } else {
  70.         if (is_inconclusive_context_free(dict)) {
  71.             std::cout << "23" << std::endl;
  72.         } else if (is_context_free(dict)) {
  73.             std::cout << "2" << std::endl;
  74.         } else {
  75.             std::cout << "10" << std::endl;
  76.         }
  77.     }
  78. }
Advertisement
Add Comment
Please, Sign In to add comment