本题可以直接采用模拟的方法,不过要注意输出的规则和格式。**输入SHELVE后输出的顺序也是按照先作者后书名的方式。**其余想记录的地方就是采用substr截取所需数据,很实用。
题目链接:UVa 230
AC代码:
#include <iostream>
#include <sstream>
#include <algorithm>
#include <vector>
#include <map>
using namespace std;
const int maxn = 1000;
struct Book {
string title, author;
bool operator < (const Book& a) {
if (author != a.author)
return author < a.author;
return title < a.title;
}
}book;
vector<Book> b, b_c;
vector<Book>::iterator it;
vector<string> back;
map<string, string> match;
bool cmp(const string& a, const string& b) {
return match[a] < match[b] || (match[a] == match[b] && a < b);
}
void bo(string title) {
int n = b.size();
for (it = b.begin(); it != b.end(); it++)
if ((*it).title == title) {
b.erase(it);
sort(b.begin(), b.end());
break;
}
}
void re(string title) {
int n = b_c.size();
for (int i = 0; i < b.size(); i++) { //如果该书已经在图书馆中,则拒绝归还
if (b[i].title == title)
return;
}
for (int i = 0; i < n; i++)
if (b_c[i].title == title) {
book.title = title;
book.author = b_c[i].author;
back.push_back(title); //加入还书数组
b.push_back(book);
sort(b.begin(), b.end());
break;
}
}
void sh() {
int n = back.size();
sort(back.begin(), back.end(), cmp);
for (int i = 0; !back.empty(); )
for (int j = 0; j < b.size(); j++)
if (back[i] == b[j].title) {
if (j)
cout << "Put " << b[j].title << " after " << b[j - 1].title << endl;
else
cout << "Put " << b[j].title << " first" << endl;
back.erase(back.begin());
break;
}
cout << "END" << endl;
}
int main() {
string line, str, op;
while (getline(cin, line) && line[0] != 'E') {
int p = line.find('"', 1);
book.title = line.substr(0, p + 1);
book.author = line.substr(p + 5);
b.push_back(book);
match[book.title] = book.author;
}
sort(b.begin(), b.end());
b_c = b;
while (getline(cin, line) && line != "END") {
if (line[0] == 'S')
sh();
else {
string title = line.substr(7);
if (line[0] == 'B')
bo(title);
else
re(title);
}
}
return 0;
}