1022 Digital Library(模拟)


要注意输入输出:1.输入带空格的string类时使用getline函数
2.使用cin输入后需要使用getchar()清除行末换行符,否则下一行的输入会受影响(getline操作会多出一个空行)
3.该题在连续读取关键字时,使用getchar()可以很方便地找到换行符
4.scanf、printf的性能高于cin、cout(该题不受影响)
5.string.find()没找到时返回的是string::npos(-1)
6.需要用printf输出string类时,使用c_str()函数( printf("%s",temp.c_str() )
第一次写的时候测试点4超时
1 #include<bits/stdc++.h> 2 using namespace std; 3 int n, m; 4 typedef vector<string> info; 5 map<string, info> books; 6 int main() { 7 scanf("%d\n", &n); 8 for (int i = 0; i < n; ++ i) { 9 string id; 10 string s; 11 info temp; 12 getline(cin, id); 13 for (int j = 0; j < 5; ++ j) { 14 getline(cin, s); 15 temp.push_back(s); 16 } 17 books.insert(make_pair(id, temp)); 18 } 19 20 scanf("%d\n", &m); 21 for (int i = 0; i < m; ++ i) { 22 int operation; 23 string query; 24 scanf("%d: ", &operation); 25 getline(cin, query); 26 cout << operation << ": " << query <<endl; 27 bool flag = false; 28 if (operation == 3) { 29 for (auto book : books) { 30 if (book.second[2].find(query) != string::npos) { 31 cout << book.first << endl; 32 flag = true; 33 } 34 } 35 } else { 36 for (auto book : books) { 37 if (book.second[operation - 1] == query) { 38 cout << book.first << endl; 39 flag = true; 40 } 41 } 42 } 43 if (!flag) { 44 cout << "Not Found" << endl; 45 } 46 } 47 }
没办法,只能空间换时间了
1 #include<bits/stdc++.h> 2 using namespace std; 3 int n, m; 4 map<string, set<string>> info[5];//分别对应标题、作者、关键字、出版社、年份,set中装id 5 int main() { 6 scanf("%d\n", &n); //注意清除行末换行符,此处可用cin+getchar的组合替换 7 for (int i = 0; i < n; ++ i) { 8 string id; 9 string temp; 10 getline(cin, id); 11 for (int j = 0; j < 5; ++ j) { 12 if (j == 2) { 13 while(cin >> temp) { 14 info[j][temp].insert(id); 15 char c = getchar(); 16 if (c == '\n') { 17 break; 18 } 19 } 20 } else { 21 getline(cin, temp); 22 info[j][temp].insert(id); 23 } 24 } 25 } 26 scanf("%d\n", &m); 27 for (int i = 0; i < m; ++ i) { 28 int operation; 29 string query; 30 scanf("%d: ", &operation); 31 getline(cin, query); 32 cout << operation << ": " << query <<endl; 33 if (info[operation - 1].find(query) != info[operation - 1].end()) { 34 auto s = info[operation - 1].find(query) -> second; 35 for (auto id : s) { 36 cout << id << endl; 37 } 38 } else { 39 cout << "Not Found" << endl; 40 } 41 } 42 }
浙公网安备 33010602011771号