Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <algorithm>
- #include <iostream>
- #include <set>
- #include <string>
- #include <utility>
- #include <vector>
- using namespace std;
- const int MAX_RESULT_DOCUMENT_COUNT = 5; // Максимальное количество документов для вывода в результат
- // Прочесть строку с входного потока
- string ReadLine()
- {
- string s;
- getline(cin, s);
- return s;
- }
- // Прочесть целочисленное значение с входного потока
- int ReadLineWithNumber()
- {
- int result = 0;
- // Считать число из входного потока
- cin >> result;
- // Считать символы возврата каретки и перевода строки
- ReadLine();
- return result;
- }
- // Разделяет строку на слова
- vector<string> SplitIntoWords(const string& text)
- {
- vector<string> words;
- string word;
- for (const char c : text)
- {
- if (c == ' ')
- {
- if (!word.empty())
- {
- words.push_back(word);
- word.clear();
- }
- }
- else
- {
- word += c;
- }
- }
- if (!word.empty())
- {
- words.push_back(word);
- }
- return words;
- }
- // Формат данных, в котором поисковый сервер возвращает единицу результата поиска
- struct Document
- {
- int id;
- int relevance;
- };
- //
- bool HasDocumentGreaterRelevance(const Document& lhs, const Document& rhs)
- {
- return lhs.relevance > rhs.relevance;
- }
- // Класс поискового сервера
- class SearchServer
- {
- private:
- // Структура документа
- struct DocumentContent
- {
- int id = 0; // Идентификатор докумена
- vector<string> words; // Вектор слов из которых состоит документ
- };
- vector<DocumentContent> documents; // Вектор документов
- set<string> stop_words; // Множество стоп-слов
- private:
- // Разделяет строку на слова исключая стоп-слова
- vector<string> SplitIntoWordsNoStop(const string& text);
- // Находит все документы подходящие под запрос
- vector<Document> FindAllDocuments(const set<string>& query_words);
- // Выдаёт соответствующую запросу релевантность документа
- static int MatchDocument(const DocumentContent& content, const set<string>& query_words);
- // Распарсить запрос
- set<string> ParseQuery(const string& text);
- public:
- // Добавляет стоп-слова в поле stop_words
- void SetStopWords(const string& text);
- // Добавляет новый документ в вектор
- void AddDocument(int document_id, const string& document);
- // Выдаёт "топ" документов
- vector<Document> FindTopDocuments(const string& raw_query);
- };
- set<string> SearchServer::ParseQuery(const string& text)
- {
- set<string> query_words;
- for (const string& word : SplitIntoWordsNoStop(text))
- {
- query_words.insert(word);
- }
- return query_words;
- }
- void SearchServer::SetStopWords(const string& text)
- {
- for (const string& word : SplitIntoWords(text))
- {
- stop_words.insert(word);
- }
- }
- // Добавляет новый документ в вектор
- void SearchServer::AddDocument(int document_id, const string& document)
- {
- const vector<string> words = SplitIntoWordsNoStop(document);
- documents.push_back({ document_id, words });
- }
- // Разделяет строку на слова исключая стоп-слова
- vector<string> SearchServer::SplitIntoWordsNoStop(const string& text)
- {
- vector<string> words;
- for (const string& word : SplitIntoWords(text))
- {
- if (stop_words.count(word) == 0)
- {
- words.push_back(word);
- }
- }
- return words;
- }
- // Выдаёт "топ" документов
- vector<Document> SearchServer::FindTopDocuments(const string& raw_query)
- {
- const set<string> query_words = ParseQuery(raw_query);
- auto matched_documents = FindAllDocuments(query_words);
- sort(matched_documents.begin(), matched_documents.end(), HasDocumentGreaterRelevance);
- if (matched_documents.size() > MAX_RESULT_DOCUMENT_COUNT)
- {
- matched_documents.resize(MAX_RESULT_DOCUMENT_COUNT);
- }
- return matched_documents;
- }
- // Находит все документы подходящие под строку запроса
- vector<Document> SearchServer::FindAllDocuments(const set<string>& query_words)
- {
- vector<Document> matched_documents; // Соответствующие документы
- // Цикл по всем документам
- for (const auto& document : documents)
- {
- // Получение релевантности для текущего документа
- const int relevance = MatchDocument(document, query_words);
- if (relevance > 0)
- {
- matched_documents.push_back({ document.id, relevance });
- }
- }
- return matched_documents;
- }
- // Создает экземпляр класса поискового сервера с инициализацией
- SearchServer CreateSearchServer()
- {
- SearchServer search_server; // Создает экземпляр класса
- // Считать и записать стоп-слова
- search_server.SetStopWords(ReadLine());
- // Считать кол-во документов
- const int document_count = ReadLineWithNumber();
- // В цикле считать и записать документы
- for (int document_id = 0; document_id < document_count; ++document_id)
- {
- search_server.AddDocument(document_id, ReadLine());
- }
- return search_server;
- }
- // Выдаёт соответствующую запросу релевантность документа
- static int SearchServer::MatchDocument(const DocumentContent& content, const set<string>& query_words)
- {
- // Проверка на пустые входные данные (пустую строку запроса)
- if (query_words.empty())
- {
- return 0;
- }
- set<string> matched_words; // Здесь будем хранить множество совпавших слов
- // Цикл по словам документа
- for (const string& word : content.words)
- {
- // Исключить повторяющиеся слова
- if (matched_words.count(word) != 0)
- {
- continue;
- }
- // Если слово из документа совпало с одним из слов в запросе
- if (query_words.count(word) != 0)
- {
- // Добавить совпавшее слово
- matched_words.insert(word);
- }
- }
- // Возвращаем количество совпадений
- return static_cast<int>(matched_words.size());
- }
- //
- int main()
- {
- // Создаём экземпляр поискового сервера
- SearchServer search_server = CreateSearchServer();
- // Считываем строку запроса
- const string query = ReadLine();
- // Находим и выводим релевантные документы
- for ( auto[document_id, relevance] : search_server.FindTopDocuments(query) )
- {
- cout << "{ document_id = "s << document_id << ", relevance = "s << relevance << " }"s << endl;
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment