1 //#include<bits/stdc++.h> 2 #include<cstdio> 3 #include<queue> 4 #include<algorithm> 5 #include<cstring> 6 #include<string> 7 #include<iostream> 8 using namespace std; 9 typedef long long ll; 10 /** 11 题意:SHELVE指令表示把所有已归还但还未上架的图书排序后依次插入书架 12 排序方法:先作者从小到大,再标题从小到大 13 需要用到一些string类的方法 ,如果用C,需要用到cstring的一些方法 14 思路: 15 结构体Book保存信息,status表示图书状态,放入vector中 16 17 上面那个思路龊了,但因为懒,代码就不改了 18 ************** 19 :加入用vector保存图书信息,在还书和借书改变status时,需要遍历vector,妈呀太浪费资源了 20 正确的姿势应该是 21 用vector<string> title 保存书名 22 用map<string,book> books K:书名 V:book中存放 author和 status 23 这样在排序vector时:vector用 map里的信息排序 24 bool compare(string a, string b){ 25 if(books[a].author == books[b].author) return a < b; 26 else return books[a].author < books[b].author; 27 } 28 SHELVE操作时候 29 for(int i = 0; i < title.size(); i++) 30 if(books[title[i]].status == 0){ 31 int j; 32 for(j = i; j >= 0; --j) 33 if(books[title[j]].status == 1) break; 34 } 35 */ 36 struct Book{ 37 string title; 38 string author; 39 int status; 40 }; 41 bool cmp(Book b1,Book b2){ 42 if(b1.author == b2.author) 43 return b1.title < b2.title; 44 return b1.author < b2.author; 45 } 46 vector<Book> vec; 47 int main(){ 48 49 string str,op,name,title,author; 50 while(getline(cin,str)){ 51 if(str == "END") break; 52 int pos = str.find_last_of("\""); 53 title = str.substr(0,pos+1); //不包含pos 54 author = str.substr(pos+5); //包含pos 55 Book tmp; tmp.author = author; tmp.title = title; 56 tmp.status = 1; 57 vec.push_back(tmp); 58 } 59 sort(vec.begin(),vec.end(),cmp); 60 while(cin >> op){ 61 if(op == "END") break; 62 getchar(); 63 if(op == "BORROW"){ 64 getline(cin,name); 65 for(int i = 0 ; i < vec.size() ; i ++){ 66 if(vec[i].title == name){ 67 vec[i].status = -1; 68 break; 69 } 70 } 71 }else if(op == "RETURN"){ 72 getline(cin,name); 73 for(int i = 0 ; i < vec.size() ; i ++){ 74 if(vec[i].title == name){ 75 vec[i].status = 0; 76 break; 77 } 78 } 79 }else if(op == "SHELVE"){ 80 for(int i = 0 ; i < vec.size() ; i ++){ 81 int index1 = 0 , index2 = -1; 82 if(vec[i].status == 0){ 83 index1 = i; 84 for(int j = index1 - 1 ; j >= 0 ; j --){ 85 if(vec[j].status == 1){ 86 index2 = j; 87 break; 88 } 89 } 90 if(index2 == -1) cout << "Put " << vec[index1].title << " first" << endl; 91 else cout << "Put " << vec[index1].title << " after " << vec[index2].title << endl; 92 vec[index1].status = 1; 93 } 94 } 95 cout << "END" << endl; 96 } 97 } 98 return 0; 99 }
时间: 2024-10-14 12:46:09