UVa 230 - Borrowers

题目

模拟图书馆图书的借用状态。书有三种状态:1在图书馆的书架上,2被接走了,3刚还回来还没有放到书架上。每次有三种操作:1借书,2还书,3把换回来的书放回书架。

分析

模拟。数据较小,直接枚举查找即可,使用map存储标记。

说明

注意每次“SHELVE”输出END

#include 
#include 
#include 
#include   
#include 
#include 

using namespace std;

typedef struct _book
{
    char title[99];
    char author[99];
    friend bool operator < (_book a, _book b) 
    {
        if (strcmp(a.author, b.author)) {
            return strcmp(a.author, b.author) < 0;
        }else {
            return strcmp(a.title, b.title) < 0;
        }
    }
}book;
book Book[1111];
map <string, string> book_state;

int main()
{
    char buf[99], book_title[99];
    int  book_size = 0;
    book_state.clear();
    while (gets(buf) && strcmp(buf, "END")) {
        int position = strchr(buf+1, '"') - buf;
        strncpy(Book[book_size].title, buf, position+1);
        position = strstr(buf+position, "by") - buf;
        strcpy(Book[book_size].author, buf+position+3);
        book_state[Book[book_size].title] = "SHELVE";
        book_size ++;
    }
    sort(Book, Book+book_size);
    while (gets(buf) && strcmp(buf, "END")) {
        if ('B' == buf[0]) {
            strcpy(book_title, buf+strlen("BORROW "));
            book_state[book_title] = "BORROW";
        }else if ('R' == buf[0]) {
            strcpy(book_title, buf+strlen("RETURN "));
            book_state[book_title] = "RETURN";
        }else if ('S' == buf[0]) {
            for (int i = 0; i < book_size; ++ i) {
                if (book_state[Book[i].title] == "RETURN") {
                    book_state[Book[i].title] = "SHELVE";
                    int index = -1;
                    for (int j = i-1; j >= 0; -- j) {
                        if (book_state[Book[j].title] == "SHELVE") {
                            index = j;
                            break;
                        }
                    }
                    if(index == -1) {  
                        printf("Put %s first\n", Book[i].title);  
                    }else {
                        printf("Put %s after %s\n", Book[i].title, Book[index].title);  
                    }
                }
            }
            printf("END\n"); 
        }
    }
    return 0;
}

你可能感兴趣的:(解题报告,字符串)