shizaero

Untitled

Apr 1st, 2023
177
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 12.18 KB | None | 0 0
  1. #include <algorithm>
  2. #include <cmath>
  3. #include <iostream>
  4. #include <map>
  5. #include <set>
  6. #include <string>
  7. #include <utility>
  8. #include <vector>
  9.  
  10. using namespace std;
  11.  
  12. const int MAX_RESULT_DOCUMENT_COUNT = 5;
  13.  
  14.  
  15. string ReadLine() {
  16.     string s;
  17.     getline(cin, s);
  18.     return s;
  19. }
  20.  
  21. int ReadLineWithNumber() {
  22.     int result;
  23.     cin >> result;
  24.     ReadLine();
  25.     return result;
  26. }
  27.  
  28. vector<string> SplitIntoWords(const string& text) {
  29.     vector<string> words;
  30.     string word;
  31.     for (const char c : text) {
  32.         if (c == ' ') {
  33.             if (!word.empty()) {
  34.                 words.push_back(word);
  35.                 word.clear();
  36.             }
  37.         }
  38.         else {
  39.             word += c;
  40.         }
  41.     }
  42.     if (!word.empty()) {
  43.         words.push_back(word);
  44.     }
  45.  
  46.     return words;
  47. }
  48.  
  49. struct Document {
  50.     Document() = default;
  51.  
  52.     Document(int id, double relevance, int rating)
  53.         : id(id)
  54.         , relevance(relevance)
  55.         , rating(rating) {
  56.     }
  57.  
  58.     int id = 0;
  59.     double relevance = 0.0;
  60.     int rating = 0;
  61. };
  62.  
  63. template <typename StringContainer>
  64. set<string> MakeUniqueNonEmptyStrings(const StringContainer& strings) {
  65.     set<string> non_empty_strings;
  66.     for (const string& str : strings) {
  67.         if (!str.empty()) {
  68.             non_empty_strings.insert(str);
  69.         }
  70.     }
  71.     return non_empty_strings;
  72. }
  73.  
  74. enum class DocumentStatus {
  75.     ACTUAL,
  76.     IRRELEVANT,
  77.     BANNED,
  78.     REMOVED,
  79. };
  80. class StopWords {
  81. public:
  82.  
  83.     StopWords() = default;
  84.  
  85.     StopWords(const string& text) {
  86.         for (const string& word : SplitIntoWords(text)) {
  87.             stop_words.insert(word);
  88.         }
  89.     }
  90.  
  91.     template <typename Container>
  92.     StopWords(const Container& container) {
  93.         for (const auto& element : container) {
  94.             if (!element.empty()) {
  95.                 stop_words.insert(element);
  96.             }
  97.         }
  98.     }
  99.  
  100.     bool IsStopWord(const string& word) const {
  101.         return stop_words.count(word) > 0;
  102.     }
  103.  
  104. private:
  105.     set<string> stop_words = { ""s };
  106. };
  107.  
  108. class SearchServer {
  109. public:
  110.     inline static constexpr int INVALID_DOCUMENT_ID = -1;
  111.  
  112.     template <typename StringContainer>
  113.     explicit SearchServer(const StringContainer& stop_words)
  114.         : stop_words_(MakeUniqueNonEmptyStrings(stop_words)) {
  115.     }
  116.  
  117.     explicit SearchServer(const string& stop_words_text)
  118.         : SearchServer(
  119.             SplitIntoWords(stop_words_text))  // Invoke delegating constructor from string container
  120.     {
  121.     }
  122.  
  123.     [[nodiscard]] bool AddDocument(int document_id, const string& document, DocumentStatus status,
  124.         const vector<int>& ratings) {
  125.         if (document_id < 0 or documents_.count(document_id) > 0 or IsValidWord(document) == false) {
  126.             //cout << "error" << endl;
  127.             return false;
  128.         }
  129.  
  130.         const vector<string> words = SplitIntoWordsNoStop(document);
  131.         const double inv_word_count = 1.0 / words.size();
  132.         for (const string& word : words) {
  133.             word_to_document_freqs_[word][document_id] += inv_word_count;
  134.         }
  135.         documents_.emplace(document_id, DocumentData{ ComputeAverageRating(ratings), status });
  136.  
  137.         //cout << "pass" << endl;
  138.         count_documents_.push_back(document_id);
  139.         return true;
  140.     }
  141.  
  142.     template <typename DocumentPredicate>
  143.     [[nodiscard]] bool FindTopDocuments(const string& raw_query,
  144.         DocumentPredicate document_predicate, vector<Document>& result) const {
  145.  
  146.         Query query;
  147.         if (!ParseQuery(raw_query, query)) {
  148.             return false;
  149.         }
  150.  
  151.         auto matched_documents = FindAllDocuments(query, document_predicate);
  152.  
  153.         sort(matched_documents.begin(), matched_documents.end(),
  154.             [](const Document& lhs, const Document& rhs) {
  155.                 if (abs(lhs.relevance - rhs.relevance) < 1e-6) {
  156.                     return lhs.rating > rhs.rating;
  157.                 }
  158.                 else {
  159.                     return lhs.relevance > rhs.relevance;
  160.                 }
  161.             });
  162.         if (matched_documents.size() > MAX_RESULT_DOCUMENT_COUNT) {
  163.             matched_documents.resize(MAX_RESULT_DOCUMENT_COUNT);
  164.         }
  165.         if (matched_documents.empty()) {
  166.             return false;
  167.         }
  168.         result = matched_documents;
  169.         return true;
  170.     }
  171.  
  172.     [[nodiscard]] bool FindTopDocuments(const string& raw_query, DocumentStatus status, vector<Document>& result) const {
  173.         return FindTopDocuments(
  174.             raw_query, [status](int document_id, DocumentStatus document_status, int rating) {
  175.                 return document_status == status;
  176.             }, result);
  177.     }
  178.  
  179.     [[nodiscard]] bool FindTopDocuments(const string& raw_query, vector<Document>& result) const {
  180.         return FindTopDocuments(raw_query, DocumentStatus::ACTUAL, result);
  181.     }
  182.  
  183.     int GetDocumentCount() const {
  184.         return documents_.size();
  185.     }
  186.  
  187.     int GetDocumentId(int index) const {
  188.         if (index < 0 || index >= static_cast<int>(count_documents_.size())) {
  189.             return INVALID_DOCUMENT_ID;
  190.         }
  191.         return count_documents_[index];
  192.     }
  193.  
  194.     [[nodiscard]] bool MatchDocument(const string& raw_query, int document_id, tuple<vector<string>, DocumentStatus>& result) const {
  195.         Query query;
  196.  
  197.         if (!ParseQuery(raw_query, query)) {
  198.             return false;
  199.         }
  200.         vector<string> match_words;
  201.  
  202.         for (const auto& plus : query.plus_words) {
  203.             if (!word_to_document_freqs_.count(plus) == 0 && word_to_document_freqs_.at(plus).count(document_id)) {
  204.                 match_words.push_back(plus);
  205.             }
  206.         }
  207.         for (const auto& minus : query.minus_words) {
  208.             if ((!word_to_document_freqs_.count(minus) == 0 && word_to_document_freqs_.at(minus).count(document_id))) {
  209.                 match_words.clear();
  210.                 break;
  211.             }
  212.         }
  213.  
  214.         result = { match_words, documents_.at(document_id).status };
  215.         return true;
  216.     }
  217.  
  218.     static bool IsValidWord(const string& word) {
  219.         // A valid word must not contain special characters
  220.         return none_of(word.begin(), word.end(), [](char c) {
  221.             return c >= '\0' && c < ' ';
  222.             });
  223.     }
  224.  
  225. private:
  226.     struct DocumentData {
  227.         int rating;
  228.         DocumentStatus status;
  229.     };
  230.  
  231.     StopWords stop_words_;
  232.     vector<int> count_documents_;
  233.     map<string, map<int, double>> word_to_document_freqs_;
  234.     map<int, DocumentData> documents_;
  235.  
  236.  
  237.     vector<string> SplitIntoWordsNoStop(const string& text) const {
  238.         vector<string> words;
  239.         for (const string& word : SplitIntoWords(text)) {
  240.             if (!stop_words_.IsStopWord(word)) {
  241.                 words.push_back(word);
  242.             }
  243.         }
  244.         return words;
  245.     }
  246.  
  247.     static int ComputeAverageRating(const vector<int>& ratings) {
  248.         if (ratings.empty()) {
  249.             return 0;
  250.         }
  251.         int rating_sum = 0;
  252.         for (const int rating : ratings) {
  253.             rating_sum += rating;
  254.         }
  255.         return rating_sum / static_cast<int>(ratings.size());
  256.     }
  257.  
  258.     struct QueryWord {
  259.         string data;
  260.         bool is_minus;
  261.         bool is_stop;
  262.     };
  263.  
  264.     [[nodiscard]] bool ParseQueryWord(string text, QueryWord& queryWord) const {
  265.         bool is_minus = false;
  266.         // Word shouldn't be empty
  267.         if (text[0] == '-' && static_cast<int>(text.size()) == 1) {
  268.             return false;
  269.         }
  270.         if (text[0] == '-' && text[1] == '-') {
  271.             return false;
  272.         }
  273.         if (text[static_cast<int>(text.size()) - 1] == '-') {
  274.             return false;
  275.         }
  276.         if (text[0] == '-') {
  277.             is_minus = true;
  278.             text = text.substr(1);
  279.             if (!IsValidWord(text)) {
  280.                 return  false;
  281.             }
  282.         }
  283.         queryWord = { text, is_minus, stop_words_.IsStopWord(text) };
  284.         return true;
  285.     }
  286.  
  287.     struct Query {
  288.         set<string> plus_words;
  289.         set<string> minus_words;
  290.     };
  291.  
  292.     [[nodiscard]] bool ParseQuery(const string& text, Query& query) const {
  293.        
  294.         auto split_words = SplitIntoWords(text);
  295.         for (const string& word : split_words) {
  296.             if (!IsValidWord(word)) {
  297.                 return false;
  298.             }
  299.             QueryWord query_word;
  300.             if (!ParseQueryWord(word, query_word)) {
  301.                 return false;
  302.             }
  303.             if (!query_word.is_stop) {
  304.                 if (query_word.is_minus) {
  305.                     query.minus_words.insert(query_word.data);
  306.                 }
  307.                 else {
  308.                     query.plus_words.insert(query_word.data);
  309.                 }
  310.             }
  311.         }
  312.         return true;
  313.     }
  314.  
  315.     // Existence required
  316.     double ComputeWordInverseDocumentFreq(const string& word) const {
  317.         return log(GetDocumentCount() * 1.0 / word_to_document_freqs_.at(word).size());
  318.     }
  319.  
  320.     template <typename DocumentPredicate>
  321.     vector<Document> FindAllDocuments(const Query& query,
  322.         DocumentPredicate document_predicate) const {
  323.         map<int, double> document_to_relevance;
  324.         for (const string& word : query.plus_words) {
  325.             if (word_to_document_freqs_.count(word) == 0) {
  326.                 continue;
  327.             }
  328.             const double inverse_document_freq = ComputeWordInverseDocumentFreq(word);
  329.             for (const auto [document_id, term_freq] : word_to_document_freqs_.at(word)) {
  330.                 const auto& document_data = documents_.at(document_id);
  331.                 if (document_predicate(document_id, document_data.status, document_data.rating)) {
  332.                     document_to_relevance[document_id] += term_freq * inverse_document_freq;
  333.                 }
  334.             }
  335.         }
  336.  
  337.         for (const string& word : query.minus_words) {
  338.             if (word_to_document_freqs_.count(word) == 0) {
  339.                 continue;
  340.             }
  341.             for (const auto [document_id, _] : word_to_document_freqs_.at(word)) {
  342.                 document_to_relevance.erase(document_id);
  343.             }
  344.         }
  345.  
  346.         vector<Document> matched_documents;
  347.         for (const auto [document_id, relevance] : document_to_relevance) {
  348.             matched_documents.push_back(
  349.                 { document_id, relevance, documents_.at(document_id).rating });
  350.         }
  351.         return matched_documents;
  352.     }
  353. };
  354.  
  355. void PrintDocument(const Document& document) {
  356.     cout << "{ "s
  357.         << "document_id = "s << document.id << ", "s
  358.         << "relevance = "s << document.relevance << ", "s
  359.         << "rating = "s << document.rating << " }"s << endl;
  360. }
  361. int main() {
  362.     SearchServer search_server("и в на"s);
  363.     // Явно игнорируем результат метода AddDocument, чтобы избежать предупреждения
  364.     // о неиспользуемом результате его вызова
  365.     (void)search_server.AddDocument(1, "пушистый кот пушистый хвост"s, DocumentStatus::ACTUAL, { 7, 2, 7 });
  366.     if (!search_server.AddDocument(1, "пушистый пёс и модный ошейник"s, DocumentStatus::ACTUAL, { 1, 2 })) {
  367.         cout << "Документ не был добавлен, так как его id совпадает с уже имеющимся"s << endl;
  368.     }
  369.     if (!search_server.AddDocument(-1, "пушистый пёс и модный ошейник"s, DocumentStatus::ACTUAL, { 1, 2 })) {
  370.         cout << "Документ не был добавлен, так как его id отрицательный"s << endl;
  371.     }
  372.     if (!search_server.AddDocument(3, "большой пёс скво\x12рец"s, DocumentStatus::ACTUAL, { 1, 3, 2 })) {
  373.         cout << "Документ не был добавлен, так как содержит спецсимволы"s << endl;
  374.     }
  375.     vector<Document> documents;
  376.     if (search_server.FindTopDocuments("--пушистый"s, documents)) {
  377.         for (const Document& document : documents) {
  378.             PrintDocument(document);
  379.         }
  380.     }
  381.     else {
  382.         cout << "Ошибка в поисковом запросе"s << endl;
  383.     }
  384. }
Advertisement
Add Comment
Please, Sign In to add comment