UVA-230《算法竞赛入门经典》

来源:互联网 发布:可达矩阵求解过程 编辑:程序博客网 时间:2024/05/21 18:18

原题链接: UVA-230

题目大意:

 模拟图书管理系统,首先输入若干图书的标题和作者(标题各不相同,以END结束),然后是若干指令:borrow指令表示借书,return指令表示还书,shelve指令表示把所以已归还但还没有上架的图书排序后插入书架并输入图书标题和插入位置(可能是第一本书或者某本书的后面),图书排序的方法是先按作者从小到大排序,再按标题从小到大排序。在处理第一条指令前,应当先将所有图书按照这种方式排序。

解题思路:

 本题是《算法竞赛入门经典》第五章c++与STL的课后题,所以我当然首先想如何需要用什么STL容器去解决问题,经过思考和参考网上的解题思路之后,我决定使用map对图书的状态进行模拟,再使用vector对结构体book进行存储,节省存储空间。


 选择好用什么容器之后,问题就集中到了如何处理输入字符串还有如何在shelve的时候找到应该插入的位置。对于输入字符串的处理,我参考了别的pong友的思路,先用string的find函数找到第二个双引号的位置,然后用substr截取。对于如何找到应该插入的位置,应该从该书排序之后的序号,通过map开始向前查找,找到的第一个在架的书,然后插到后面,若前面已经没有书了,那就放在第一个。

遇到问题:

 WA了多次,很无奈。对了accpted output,发现是输出格式首字母没有大写,MMP。。。

感悟:

 第一次写博客,不足之处请见谅。


                                                               

代码:

#include<iostream>#include<string>#include<sstream>#include<map>#include<vector>#include<algorithm> using namespace std;struct Book{string title;string author;Book(string n,string a){title = n;author = a;}bool operator< (const Book b){if(this->author == b.author)return this->title < b.title;return this->author < b.author;}};map<string,int> value;//存放图书当前状态1:在架,2:归还未上架,0:借出vector<Book> books;//用于存储图书 int main(){//freopen("input.txt","r",stdin);//freopen("output.txt","w",stdout);string s,title,author;while(getline(cin,s) && s != "END"){int pos = s.find('\"',1);title = s.substr(1,pos);pos += 5;author = s.substr(pos);Book b = Book(title,author);books.push_back(b);value[title] = 1;}sort(books.begin(),books.end());//对书进行升序排序 while(getline(cin,s) && s != "END"){if(s[0] == 'B'){title = s.substr(8);value[title] = 0;//书借走之后要将标记记为0 }else if(s[0] == 'R'){title = s.substr(8);value[title] = 2;//归还未上架的书记为2 } else{for(int i = 0 ; i < books.size() ; i++){if(value[books[i].title] == 2){int j;for(j = i-1 ; j >= 0 ;j--)//找到当前第i本书应该插入的位置j {if(value[books[j].title] == 1)break;}cout << "Put \""<<books[i].title<<" ";if(j != -1)cout << "after \"" <<books[j].title <<endl;else  cout << "first" <<endl;value[books[i].title] = 1;}}cout << "END\n";} }return 0;} 



原创粉丝点击