Задача: разработать программу с оптимальным хранением в памяти с использованием AVL-дерева. Программа реализует простую базу данных, которая хранит набор книг из онлайн-библиотеки и предоставляет пользователю удобный консольный интерфейс взаимодействия.
Каждая книга описывается следующими полями:
Название книги.
Автор/Авторы.
Год выпуска.
Оценка читателей.
Цена книги.
Жанр.
Допускается использование различных служебных полей (к примеру, внутреннего идентификатора книги).
Программа должна поддерживать ряд операций, а именно:
Добавление книги.
Удаление книги.
Редактирование книги.
Поиск по любому из полей по всей базе данных.
Вывод информации о книгах.
Требования:
Книги могут описаны как на русском языке, так и на английском.
Использование наиболее оптимального дерева для реализации программы.
Программа запускается и ожидает на вход набор команд.
Команды, которые поступают на вход, имеют следующий формат:
ADD «Название книги» «Автор/Авторы» (разделяются запятыми) «Год выпуска» «Оценка читателей» «Цена книги» «Жанр». Если указанной книги еще нет в дереве, вставить и вывести слово «ADD_DONE», если уже есть — оставить дерево как было и выводить слово «ADD_ALREADY».
DELETE «Название книги». Если указанная книга есть в дереве, удалить и вывести слово «DELETE_DONE», если нет — оставить дерево как было и выводить слово «DELETE_CANNOT».
SEARCH item, где item это одно из полей книги. Ответ «YES/NO».
EDIT «Название книги»: «Название книги» «Автор/Авторы» (разделяются запятыми) «Год выпуска» «Оценка читателей» «Цена книги» «Жанр». Эта команда меняет какой-то параметр книги. Панков не написал, как именно писать это в командной строке. Решаем сами
LNRPRINTTREE, вывод — обход LNR. Новая строка не указывается. Вывод осуществляется в соответствии с полями книги, описанными выше.
NLRPRINTTREE, вывод — обход NLR. Новая строка не указывается. Вывод осуществляется в соответствии с полями книги, описанными выше.
LRNPRINTTREE, вывод — обход LRN. Новая строка не указывается. Вывод осуществляется в соответствии с полями книги, описанными выше.
В случае некорректного ввода программа выводит «Error parse».
Между словами может быть неограниченное число пробелов.
При компиляции программы не должно быть никаких предупреждений от компилятора (для удобства можно использовать ключи компиляции /Wall, /WX для Visual Studio; -Wall -pedantic для GCC).
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Below is a C++ program that fulfills the requirements you've outlined. The program uses an AVL tree to store books, ensuring optimal memory usage and efficient operations. The code is structured to handle all specified commands, including error parsing and various tree traversal methods.
Overview
Book Structure: Each book is represented by a Book structure containing all necessary fields. The titles are used as unique keys for the AVL tree.
AVL Tree Implementation: The AVL tree ensures that the tree remains balanced after every insertion and deletion, providing O(log n) time complexity for these operations.
Command Parsing: The program reads commands from the console input, parses them, and executes the corresponding operations. It handles incorrect input gracefully by outputting "Error parse".
Traversal Methods: The program supports in-order (LNR), pre-order (NLR), and post-order (LRN) traversals, outputting the books' information accordingly.
Compilation: The program is written to compile without warnings using both GCC and Visual Studio with the appropriate flags.
Complete Code
cpp
#include <bits/stdc++.h>
#include <string>
#include <vector>
#include <sstream>
using namespace std;
// Book structure
struct Book {
string title;
vector<string> authors;
int year;
double rating;
double price;
string genre;
// For AVL tree ordering based on title
bool operator<(const Book& other) const {
return title < other.title;
}
bool operator==(const Book& other) const {
return title == other.title;
}
// Convert Book to string for printing
string toString() const {
string authors_str;
for(size_t i = 0; i < authors.size(); ++i){
authors_str += authors[i];
if(i != authors.size() -1) authors_str += ",";
}
// Using space as separator as per requirement (can be adjusted)
return "\"" + title + "\" \"" + authors_str + "\" \"" + to_string(year) + "\" \"" +
to_string(rating) + "\" \"" + to_string(price) + "\" \"" + genre + "\"";
}
};
// AVL Tree Node
struct AVLNode {
Book book;
AVLNode* left;
AVLNode* right;
int height;
AVLNode(const Book& b)
: book(b), left(nullptr), right(nullptr), height(1) {}
};
// AVL Tree Class
class AVLTree {
private:
AVLNode* root;
// Get height of node
int getHeight(AVLNode* node) {
return node ? node->height : 0;
}
// Get balance factor
int getBalance(AVLNode* node) {
if (!node) return 0;
return getHeight(node->left) - getHeight(node->right);
}
// Right rotate
AVLNode* rightRotate(AVLNode* y) {
AVLNode* x = y->left;
AVLNode* T2 = x->right;
// Perform rotation
x->right = y;
y->left = T2;
// Update heights
y->height = max(getHeight(y->left), getHeight(y->right)) +1;
x->height = max(getHeight(x->left), getHeight(x->right)) +1;
return x;
}
// Left rotate
AVLNode* leftRotate(AVLNode* x) {
AVLNode* y = x->right;
AVLNode* T2 = y->left;
// Perform rotation
y->left = x;
x->right = T2;
// Update heights
x->height = max(getHeight(x->left), getHeight(x->right)) +1;
y->height = max(getHeight(y->left), getHeight(y->right)) +1;
return y;
}
// Insert helper
AVLNode* insertNode(AVLNode* node, const Book& book, bool& inserted) {
if (!node) {
inserted = true;
return new AVLNode(book);
}
if (book < node->book) {
node->left = insertNode(node->left, book, inserted);
}
else if (node->book < book) {
node->right = insertNode(node->right, book, inserted);
}
else {
// Duplicate title
inserted = false;
return node;
}
// Update height
node->height = 1 + max(getHeight(node->left), getHeight(node->right));
// Get balance factor
int balance = getBalance(node);
// Balancing
// Left Left
if (balance > 1 && book < node->left->book)
return rightRotate(node);
// Right Right
if (balance < -1 && node->right->book < book)
return leftRotate(node);
// Left Right
if (balance >1 && node->left->book < book){
node->left = leftRotate(node->left);
return rightRotate(node);
}
// Right Left
if (balance < -1 && book < node->right->book){
node->right = rightRotate(node->right);
return leftRotate(node);
}
return node;
}
// Find the node with minimum key value
AVLNode* minValueNode(AVLNode* node) {
AVLNode* current = node;
while(current->left)
current = current->left;
return current;
}
// Delete helper
AVLNode* deleteNode(AVLNode* node, const string& title, bool& deleted) {
if (!node) {
deleted = false;
return node;
}
if (title < node->book.title){
node->left = deleteNode(node->left, title, deleted);
}
else if (node->book.title < title){
node->right = deleteNode(node->right, title, deleted);
}
else{
// Found the node
deleted = true;
// Node with only one child or no child
if(!node->left || !node->right){
AVLNode* temp = node->left ? node->left : node->right;
if (!temp){
// No child
temp = node;
node = nullptr;
}
else{
// One child
*node = *temp;
}
delete temp;
}
else{
// Node with two children
AVLNode* temp = minValueNode(node->right);
node->book = temp->book;
node->right = deleteNode(node->right, temp->book.title, deleted);
}
}
// If the tree had only one node
if (!node)
return node;
// Update height
node->height = 1 + max(getHeight(node->left), getHeight(node->right));
// Get balance factor
int balance = getBalance(node);
// Balancing
// Left Left
if (balance >1 && getBalance(node->left) >=0)
return rightRotate(node);
// Left Right
if (balance >1 && getBalance(node->left) <0){
node->left = leftRotate(node->left);
return rightRotate(node);
}
// Right Right
if (balance < -1 && getBalance(node->right) <=0)
return leftRotate(node);
// Right Left
if (balance < -1 && getBalance(node->right) >0){
node->right = rightRotate(node->right);
return leftRotate(node);
}
return node;
}
// Search helper
bool searchField(AVLNode* node, const string& field) const {
if (!node) return false;
// Check each field
// Title
if (node->book.title == field) return true;
// Authors
for(auto &a: node->book.authors){
if (a == field) return true;
}
// Year
if (to_string(node->book.year) == field) return true;
// Rating
string rating_str = to_string(node->book.rating);
// Remove trailing zeros and dot if necessary
rating_str.erase(rating_str.find_last_not_of('0') +1, string::npos);
if (rating_str.back() == '.') rating_str.pop_back();
if (rating_str == field) return true;
// Price
string price_str = to_string(node->book.price);
price_str.erase(price_str.find_last_not_of('0') +1, string::npos);
if (price_str.back() == '.') price_str.pop_back();
if (price_str == field) return true;
// Genre
if (node->book.genre == field) return true;
// Continue searching in left and right
return searchField(node->left, field) || searchField(node->right, field);
}
// In-order traversal
void inOrder(AVLNode* node, vector<Book>& books) const {
if (node){
inOrder(node->left, books);
books.push_back(node->book);
inOrder(node->right, books);
}
}
// Pre-order traversal
void preOrder(AVLNode* node, vector<Book>& books) const {
if (node){
books.push_back(node->book);
preOrder(node->left, books);
preOrder(node->right, books);
}
}
// Post-order traversal
void postOrder(AVLNode* node, vector<Book>& books) const {
if (node){
postOrder(node->left, books);
postOrder(node->right, books);
books.push_back(node->book);
}
}
// Search by title
AVLNode* searchTitle(AVLNode* node, const string& title) const {
if (!node) return nullptr;
if (title < node->book.title)
return searchTitle(node->left, title);
else if (node->book.title < title)
return searchTitle(node->right, title);
else
return node;
}
public:
AVLTree(): root(nullptr) {}
// Insert book
bool insert(const Book& book) {
bool inserted = false;
root = insertNode(root, book, inserted);
return inserted;
}
// Delete book by title
bool deleteTitle(const string& title){
bool deleted = false;
root = deleteNode(root, title, deleted);
return deleted;
}
// Search any field
bool searchAnyField(const string& field) const {
return searchField(root, field);
}
// Edit book by title
bool editBook(const string& title, const Book& newBook){
// First, delete the old book
bool deleted = deleteTitle(title);
if (!deleted) return false;
// Then, insert the new book
bool inserted = insert(newBook);
// If insertion fails (duplicate title), rollback by re-inserting the old book
if (!inserted){
insert(searchTitle(root, title)->book);
return false;
}
return true;
}
// Get traversal lists
vector<Book> getInOrder() const {
vector<Book> books;
inOrder(root, books);
return books;
}
vector<Book> getPreOrder() const {
vector<Book> books;
preOrder(root, books);
return books;
}
vector<Book> getPostOrder() const {
vector<Book> books;
postOrder(root, books);
return books;
}
};
// Utility functions
// Trim leading and trailing spaces
string trim(const string& s){
size_t start = s.find_first_not_of(" ");
if(start == string::npos) return "";
size_t end = s.find_last_not_of(" ");
return s.substr(start, end - start +1);
}
// Parse quoted strings
bool parseQuoted(const string& s, size_t& pos, string& out){
out = "";
// Skip leading spaces
while(pos < s.size() && s[pos] == ' ') pos++;
if(pos >= s.size() || s[pos] != '\"') return false;
pos++; // skip "
while(pos < s.size() && s[pos] != '\"'){
out += s[pos];
pos++;
}
if(pos >= s.size() || s[pos] != '\"') return false;
pos++; // skip "
return true;
}
// Split authors by commas
vector<string> splitAuthors(const string& s){
vector<string> authors;
string temp;
stringstream ss(s);
while(getline(ss, temp, ',')){
authors.push_back(trim(temp));
}
return authors;
}
// Parse ADD or EDIT command fields
bool parseBookFields(const string& s, size_t pos, Book& book){
// Parse title
if(!parseQuoted(s, pos, book.title)) return false;
// Parse authors
string authors_str;
if(!parseQuoted(s, pos, authors_str)) return false;
book.authors = splitAuthors(authors_str);
// Parse year
string year_str;
if(!parseQuoted(s, pos, year_str)) return false;
try{
book.year = stoi(year_str);
}
catch(...){
return false;
}
// Parse rating
string rating_str;
if(!parseQuoted(s, pos, rating_str)) return false;
try{
book.rating = stod(rating_str);
}
catch(...){
return false;
}
// Parse price
string price_str;
if(!parseQuoted(s, pos, price_str)) return false;
try{
book.price = stod(price_str);
}
catch(...){
return false;
}
// Parse genre
if(!parseQuoted(s, pos, book.genre)) return false;
return true;
}
// Main function
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
AVLTree tree;
string line;
while(getline(cin, line)){
// Trim the line
line = trim(line);
if(line.empty()) continue;
// Parse command
size_t pos = 0;
// Find command
size_t space = line.find(' ', pos);
string command;
if(space == string::npos){
command = line;
pos = line.size();
}
else{
command = line.substr(pos, space - pos);
pos = space +1;
}
if(command == "ADD"){
Book book;
if(!parseBookFields(line, pos, book)){
cout << "Error parse\n";
continue;
}
bool inserted = tree.insert(book);
if(inserted) cout << "ADD_DONE\n";
else cout << "ADD_ALREADY\n";
}
else if(command == "DELETE"){
// Parse title
Book book;
if(!parseQuoted(line, pos, book.title)){
cout << "Error parse\n";
continue;
}
bool deleted = tree.deleteTitle(book.title);
if(deleted) cout << "DELETE_DONE\n";
else cout << "DELETE_CANNOT\n";
}
else if(command == "SEARCH"){
// Parse item
// Skip possible colon or spaces
while(pos < line.size() && line[pos] == ' ') pos++;
string item;
if(line[pos] == '\"'){
if(!parseQuoted(line, pos, item)){
cout << "Error parse\n";
continue;
}
}
else{
// Read until end
item = trim(line.substr(pos));
}
bool found = tree.searchAnyField(item);
cout << (found ? "YES\n" : "NO\n");
}
else if(command == "EDIT"){
// Expect: EDIT "Title": "New Title" "New Authors" "New Year" "New Rating" "New Price" "New Genre"
// Find ':'
size_t colon = line.find(':', pos);
if(colon == string::npos){
cout << "Error parse\n";
continue;
}
// Parse original title
Book original;
size_t temp_pos = pos;
if(!parseQuoted(line, temp_pos, original.title)){
cout << "Error parse\n";
continue;
}
// Move pos to after colon
pos = colon +1;
// Parse new book fields
Book newBook;
if(!parseBookFields(line, pos, newBook)){
cout << "Error parse\n";
continue;
}
// Ensure the original title matches newBook title or handle appropriately
// For simplicity, allow changing the title
bool edited = tree.editBook(original.title, newBook);
if(edited) cout << "EDIT_DONE\n";
else cout << "EDIT_CANNOT\n";
}
else if(command == "LNRPRINTTREE"){
vector<Book> books = tree.getInOrder();
for(size_t i =0; i < books.size(); ++i){
cout << books[i].toString();
if(i != books.size()-1) cout << "\n";
}
if(!books.empty()) cout << "\n";
}
else if(command == "NLRPRINTTREE"){
vector<Book> books = tree.getPreOrder();
for(size_t i =0; i < books.size(); ++i){
cout << books[i].toString();
if(i != books.size()-1) cout << "\n";
}
if(!books.empty()) cout << "\n";
}
else if(command == "LRNPRINTTREE"){
vector<Book> books = tree.getPostOrder();
for(size_t i =0; i < books.size(); ++i){
cout << books[i].toString();
if(i != books.size()-1) cout << "\n";
}
if(!books.empty()) cout << "\n";
}
else{
cout << "Error parse\n";
}
}
return 0;
}
Explanation
Book Structure: The Book struct holds all required fields. The toString method formats the book's data for output, ensuring that each field is enclosed in quotes and separated appropriately.
AVL Tree Implementation:
Insertion: The insert method adds a new book to the AVL tree. It uses the book's title as the unique key. If a book with the same title already exists, it doesn't insert the new book and returns false.
Deletion: The deleteTitle method removes a book based on its title. It maintains the AVL tree's balance after deletion.
Searching: The searchAnyField method allows searching for a specific item across all fields of all books.
Editing: The editBook method first deletes the existing book and then attempts to insert the updated book. If insertion fails (e.g., due to a duplicate title), it rolls back the deletion.
Traversal: The tree supports in-order (LNR), pre-order (NLR), and post-order (LRN) traversals, which are essential for different types of data retrieval.
Command Parsing:
The program reads each line from the standard input and trims unnecessary spaces.
It identifies the command and processes the arguments accordingly.
For ADD and EDIT commands, it parses the quoted strings to extract book details.
The SEARCH command looks for the provided item in any field.
The traversal commands (LNRPRINTTREE, NLRPRINTTREE, LRNPRINTTREE) output the books in the specified order.
Any unrecognized or improperly formatted command results in an "Error parse" message.
Edge Cases and Error Handling:
The program ensures that all fields are correctly quoted.
It handles cases where books to be deleted or edited do not exist.
It prevents duplicate entries based on the book title.
It gracefully handles any parsing errors by notifying the user.
Compilation:
The program is written using standard C++11 features and should compile without warnings using GCC with -Wall -pedantic flags or Visual Studio with flags.
Usage
The program reads commands from the standard input. Here’s how you can interact with it:
ADD: Add a new book.
code
ADD "The Great Gatsby" "F. Scott Fitzgerald" "1925" "4.5" "10.99" "Novel"
Output:
code
ADD_DONE
DELETE: Delete an existing book by title.
code
DELETE "The Great Gatsby"
Output:
code
DELETE_DONE
SEARCH: Search for an item across all fields.
code
SEARCH "F. Scott Fitzgerald"
Output:
code
YES
EDIT: Edit an existing book's details.
code
EDIT "The Great Gatsby": "The Great Gatsby" "Fitzgerald" "1925" "4.7" "12.99" "Classic"
Output:
code
EDIT_DONE
Traversal Commands:
In-order:
code
LNRPRINTTREE
Pre-order:
code
NLRPRINTTREE
Post-order:
code
LRNPRINTTREE
Error Handling:
If a command is improperly formatted:
code
ADD "Incomplete Book
Output:
code
Error parse
Notes
Authors Field: Multiple authors should be separated by commas within the quotes.
Titles, Authors, Genre: Strings. Titles are unique identifiers.
This implementation ensures efficient storage and retrieval of books using an AVL tree, adheres to the specified command formats, and handles edge cases gracefully.