UVA 230 Borrowers

思路:

用结构体book存作者的名字和状态,vector存所有书的名字,利用map<string,book>books(string是书名)联系书名和作者、状态;

存下来后按要求排序,输入命令进行操作 ,比如 SHELVE 操作:从前往后找还了没有上架的书,

然后从此书往前找有没有在架的书,有就放到它后面;如果找不到,说明此书是第一本。

注意:

看清楚题,连续的两个put之间不能输出END;

借和还输入的空格要处理:getchar() ,不然得到的书名前面会多一个空格。

 1 #include<iostream>
 2 #include<vector>
 3 #include<string>
 4 #include<cstring>
 5 #include<map>
 6 #include<algorithm>
 7 #include<sstream>
 8 using namespace std;
 9 #define FIN freopen("input.txt","r",stdin)
10 #define FOUT     freopen("output.txt","w",stdout)
11 struct book {
12     string auth;//作者
13     int sta;//状态
14 };
15 map<string, book> books;//<书名,book>
16 vector<string> name;
17 bool cmp(const string & s1,const string &s2)
18 {
19     if (books[s1].auth != books[s2].auth)
20         return books[s1].auth < books[s2].auth;
21     else
22         return  s1 < s2;
23 }
24 int main()
25 {
26     
27     string str;
28     int cnt = 0;
29     while (getline(cin, str)&&str!="END")//输入书
30     {
31         string  book_name;
32         book b;
33         book_name= str.substr(0, str.find_last_of('"')+1);
34         b.auth = str.substr(str.find_last_of('"') + 1);
35         //这里取到的auth是有by前面那个空格的
36         b.sta = 1;//在架
37         books[book_name] = b;
38         name.push_back(book_name);
39     }
40     
41     sort(name.begin(), name.end(), cmp);
42 
43     while (cin>>str&& str != "END")//输入操作
44     {
45         if (str == "BORROW")//借书
46         {
47             getchar();//取中间的空格
48             getline(cin, str);
49             books[str].sta = -1;//借出去
50         }
51         if (str == "RETURN")
52         {
53             getchar();
54             getline(cin, str);
55             books[str].sta = 0;//还了,未上架
56         }
57         if (str == "SHELVE")
58         {
59             for (int i = 0; i < name.size(); i++)
60             {
61                 if (books[name[i]].sta == 0)//等待上架
62                 {
63                     for (int j = i; j >= 0; j--)//找它前面在架的书
64                     {
65                         if (books[name[j]].sta == 1)//在架
66                         {
67                             cout << "Put " << name[i] << " after " << name[j] << endl;
68                             books[name[i]].sta = 1;
69                             break;
70                         }
71                         if (j == 0)//找不到,说明它是第一本
72                         {
73                             cout << "Put " << name[i] << " first" << endl;
74                             books[name[i]].sta = 1;
75                         }
76                     }
77                     
78                 }
79                 
80             }
81             cout << "END" << endl;
82         }
83     }
84 
85     return 0;
86 }

猜你喜欢

转载自www.cnblogs.com/fudanxi/p/10386212.html