题目:https://vjudge.net/problem/UVA-230
思路:对图书进行按作者和书名字典序排序,利用pair小于运算符按first、second字典序排序的特点进行存储,用书名映射作者方便还书时找到作者名,借走时将书删除,还书时按顺序排好后再放回书架,最后输出。
注意:我是掉进坑里差点出不来了,要没有同学的帮助估计真就出不来了,读题时没理解清楚这句话——
Before they are returned to the shelves, the returned
books are sorted by author and then title using the ASCII collating sequence.
return时不还书,当shelve时将return的那些书排序后再按顺序一本一本放回去。
代码:
#include <iostream>
#include <string>
#include <cstdio>
#include <iomanip>
#include <map>
#include <set>
#include <vector>
#include <deque>
#include <cstring>
#include <algorithm>
using namespace std;
map<string, string> alldata;//book name, author name所有书从书名到作者名的映射
deque<pair<string, string> > data;//author name, book name架子上现在放着的书
set<pair<string, string> > returnbook;//author name, book name换回来但还没往书架上放的书
deque<pair<string, string> >::iterator findbook(const string &book)
{
deque<pair<string, string> >::iterator it = data.begin();
for( ; it!=data.end(); it++)
{
if(it->second==book)
{
return it;
}
}
}
string getbook()
{
getchar();
char c;
c = getchar();
char str[100] = {0};
str[0] = c;
for(int i=1; ; i++)
{
c = getchar();
str[i] = c;
if(c=='"')
{
break;
}
}
string book;
book = str;
return book;
}
int main()
{
while(1)
{
char c;
c = getchar();
if(c!='"')
{
break;
}
char str[100] = {0};
str[0] = c;
for(int i=1; ; i++)
{
c = getchar();
str[i] = c;
if(c=='"')
{
break;
}
}
string book;
book = str;
getchar();
getchar();
getchar();
string name;
getline(cin, name);
data.push_back(make_pair(name, book));
alldata[book] = name;
}
sort(data.begin(), data.end());
getchar();
getchar();
while(1)
{
string order, book;
cin >> order;
if(order=="END")
{
break;
}
if(order=="BORROW")
{
book = getbook();
data.erase(findbook(book));
}
if(order=="RETURN")
{
book = getbook();
string name = alldata[book];
returnbook.insert(make_pair(name, book));
}
if(order=="SHELVE")
{
for(const auto &t:returnbook)
{
deque<pair<string, string> >::iterator it = lower_bound(data.begin(), data.end(), t);
if(it==data.begin())
{
cout << "Put " << t.second << " first" << endl;
}
else
{
cout << "Put " << t.second << " after " << (it-1)->second << endl;
}
data.insert(it, t);
}
cout << "END" << endl;
returnbook.clear();
}
}
return 0;
}