大体题意:
借书与还书,还书时要按照题目要求的排序方式进行排序,放书的位置也要输出,所以在放书之前,也得给书架上的书进行排序,放的顺序也得排序。
整体思路:
可以开个map<string, string>把书的标题映射到作者,因为标题肯定是独一无二的,但作者可以是重复的,在开两个vector<string>分别记录书架上剩余的书,和要还的书,在记录到临时结构体数组中,分别排序,最后一个一个扫描要还的书就行了。
技巧:
1.这里我把BORROW掉的书在剩余的书的vector中记作{{{因为他的ASCII码肯定是正确输入中最大的,不可能达到这个ASCII码值,所以排序时自动排到后面了,不要担心积累多了会超时,因为在{{{之前肯定会出现答案的,因为标题各不相同!
2.自顶向下,逐步求精分别写函数思路清晰即可!
代码如下:
#include<iostream>
#include<string>
#include<map>
#include<vector>
#include<algorithm>
using namespace std;
map<string,string>book;//title -> author;
vector<string>lef,shel;
const int maxn = 5000 + 10;
const string big="{{{";
struct books{string title,author;}bok[maxn],shel_bok[maxn];
bool cmp(const books&a,const books &b){return a.author<b.author || (a.author == b.author && a.title < b.title);}
void deal(){
int lef_size=lef.size(),shel_size=shel.size();
for (int i = 0; i < lef_size; ++i){bok[i].title=lef[i];bok[i].author=book[lef[i]];}
for (int i = 0; i < shel_size;++i){shel_bok[i].title=shel[i];shel_bok[i].author=book[shel[i]];}
sort(bok,bok+lef_size,cmp);
sort(shel_bok,shel_bok+shel_size,cmp);
for (int i = 0; i < shel_size; ++i){
int pos=0;
while((shel_bok[i].author > bok[pos].author || (shel_bok[i].author == bok[pos].author &&shel_bok[i].title > bok[pos].title)))++pos;
if (!pos)cout << "Put " << shel_bok[i].title << " first" << endl;
else cout << "Put " << shel_bok[i].title << " after " << bok[pos-1].title <<endl;
bok[lef_size].title=shel_bok[i].title;
bok[lef_size].author=shel_bok[i].author;lef_size++;
lef.push_back(shel_bok[i].title);
sort(bok,bok+lef_size,cmp);
}cout<<"END"<<endl;
shel.clear();
}
int main()
{
string s,key,value,t;
book["{{{"]="{{{";
while(getline(cin,s) && s != "END"){
int m=s.find("by");
key=s.substr(0,m-1);value=s.substr(m+3);
book[key]=value;
lef.push_back(key);
}
while(getline(cin,s) && s != "END"){
int m=s.find("\"");// find "
if (m==-1)deal();
else{
t=s.substr(0,m-1);
value=s.substr(m);
if (t=="BORROW"){vector<string>::iterator it = find(lef.begin(),lef.end(),value);if (it!=lef.end())*it=big;}
else shel.push_back(value);
}
}
return 0;
}