题目:Borrowers
题意:对于书架上的图书,有借出(BORROW)还回(RETURN)和上架(SHELVE)三种操作。输出SHELVE时书所放的顺序与位置。
思路:
1、将书放入结构体BOOK,用vector存储。
2、对vec排序。
3、根据输入对书的状态进行操作,-1为借出,0为待上架,1为在书架上。
4、当SHELVE时,输出。
注意:当书架上没有书时,应特殊处理。
代码:
#include<cstdio>
#include<iostream>
#include<string>
#include<vector>
#include<set>
#include<map>
#include<algorithm>
#include<cmath>
#include<queue>
using namespace std;
struct BOOK {
string Whole;
string Name;
string Author;
int state;
void Part() {
int P=Whole.find(" by ");
Name=Whole.substr(0,P);
Author=Whole.substr(P+4,Whole.size()-4-Name.size());
}
bool operator <(const BOOK& other) const {
if(Author<other.Author||(Author==other.Author&&Name<other.Name)) return true;
return false;
}
};
vector<BOOK> vec;
map<string,int> mp;
void Borrow() {
string x;
getline(cin,x);
vec[mp[x]].state=-1;
}
void Return() {
string x;
getline(cin,x);
vec[mp[x]].state=0;
}
void Shelve() {
vector<BOOK> x;
for(int i=0; i<vec.size(); i++) {
if(vec[i].state==1) {
x.push_back(vec[i]);
}
}
for(int i=0; i<vec.size(); i++) {
if(vec[i].state==0) {
if(x.empty()){
cout<<"Put "<<vec[i].Name<<" first"<<endl;
vec[i].state=1;
x.push_back(vec[i]);
sort(x.begin(),x.end());
continue;
}
for(int j=0; j<x.size(); j++) {
if(vec[i]<x[j]) {
if(j==0) cout<<"Put "<<vec[i].Name<<" first"<<endl;
else cout<<"Put "<<vec[i].Name<<" after "<<x[j-1].Name<<endl;
break;
}
}
if(x[x.size()-1]<vec[i]) cout<<"Put "<<vec[i].Name<<" after "<<x[x.size()-1].Name<<endl;
vec[i].state=1;
x.push_back(vec[i]);
sort(x.begin(),x.end());
}
}
cout<<"END\n";
}
int main() {
string x;
while(getline(cin,x)&&x[0]!='E') {
BOOK y;
y.Whole=x;
y.Part();
y.state=1;
vec.push_back(y);
}
sort(vec.begin(),vec.end());
for(int i=0; i<vec.size(); i++) {
mp[vec[i].Name]=i;
}
while(cin>>x&&x[0]!='E') {
getchar();
if(x[0]=='B') Borrow();
if(x[0]=='R') Return();
if(x[0]=='S') Shelve();
}
return 0;
}