#include <iostream>
#include <fstream>
#include <algorithm>
#include <set>
#include <string>
#include <map>
#include <cstring>
#define TEST 1
#define maxn 100
using namespace std;
struct Book
{
Book() = default;
Book(string a, string b) : author(a), title(b) {}
string author, title;
};
bool operator<(const Book &a, const Book &b)
{
return a.author < b.author ||
a.author == b.author && a.title < b.title;
}
int CNT;
bool onShelf[maxn];
map<string, int> toid;
map<int, string> totitle;
void getlist();
int main()
{
ofstream ofs;
if (TEST)
{
ofs.open("/home/lixiaoqi/Documents/Code/C++/1.txt");
if (!ofs.is_open())
throw runtime_error("FILE NOT OPEN!");
}
ostream &os = TEST ? ofs : cout;
getlist();
if (CNT >= maxn)
throw runtime_error("BEYOND!");
memset(onShelf, true, CNT * sizeof(bool));
int id;
string choice, title;
set<int> ret;
while (cin >> choice, choice != "END")
{
if (choice == "SHELVE")
{
while (ret.size())
{
id = *ret.begin();
title = totitle[id];
int bef = id - 1;
for (; bef >= 1; --bef)
if (onShelf[bef])
break;
if (id == 1 || !bef)
os << "Put " << title << " first\n";
else
os << "Put " << title << " after " << totitle[bef] << '\n';
onShelf[id] = true;
ret.erase(ret.begin());
}
os << "END\n";
}
else
{
getchar();
getline(cin, title);
if (choice == "BORROW")
onShelf[toid[title]] = false;
else if (choice == "RETURN")
ret.insert(toid[title]);
else
throw runtime_error("INPUT_ERROR!");
}
}
return 0;
}
void getlist()
{
set<Book> shelf;
string line, title, author;
while (getline(cin, line), line != "END")
{
int b = 0, e = 2;
while (line[e] != '"')
++e;
title = line.substr(b, e + 1);
author = line.substr(e + 5, line.size());
shelf.insert(Book(author, title));
}
for (set<Book>::iterator it = shelf.begin(); it != shelf.end(); ++it)
{
title = it->title;
toid[title] = ++CNT;
totitle[CNT] = title;
}
}
Sample Input
“The Canterbury Tales” by Chaucer, G.
“Algorithms” by Sedgewick, R.
“The C Programming Language” by Kernighan, B. and Ritchie, D.
END
BORROW “Algorithms”
BORROW “The C Programming Language”
RETURN “Algorithms”
RETURN “The C Programming Language”
SHELVE
END
Sample Output
Put “The C Programming Language” after “The Canterbury Tales”
Put “Algorithms” after “The C Programming Language”
END
- 106行,不需要去掉书名的引号,要灵活
- 利用map建立索引,虽然比较笨,但是用起来很爽,这也是很重要的技巧