写在前面
实现思路
map<string, set<int>>
book元数据作为键值, 书号作为值封装输入数据
其中,set<int>
避免排序问题 key words
关键词可能存在多个,空格分隔 循环读入查询类型、查询字符串,调用查询函数打印输出
函数参数使用引用
,否则可能存在超时问题(未验证,最后一组数据) 输入读取、处理较为耗时 tips
题目难度中等,45分钟内
完全可以a题
测试用例
input:
3
1111111
The Testing Book
Yue Chen
test code debug sort keywords
ZUCS Print
2011
3333333
Another Testing Book
Yue Chen
test code sort keywords
ZUCS Print2
2012
2222222
The Testing Book
CYLL
keywords debug book
ZUCS Print2
2011
6
1 : The Testing Book
2 : Yue Chen
3 : keywords
4 : ZUCS Print
5 : 2011
3 : blablabla
output:
1 : The Testing Book
1111111
2222222
2 : Yue Chen
1111111
3333333
3 : keywords
1111111
2222222
3333333
4 : ZUCS Print
1111111
5 : 2011
1111111
2222222
3 : blablabla
Not Found
ac代码
#include <map>
#include <set>
#include <string>
#include <iostream>
using namespace std;
void query ( map< string, set< int >> & mp, string& str)
{
if ( mp. find ( str) == mp. end ( ) )
printf ( "Not Found\n" ) ;
else
{
for ( set< int > : : iterator it= mp[ str] . begin ( ) ; it!= mp[ str] . end ( ) ; it++ )
printf ( "%07d\n" , * it) ;
}
}
int main ( )
{
int n, m, id, type;
scanf ( "%d" , & n) ;
string title, author, key, pub, year;
map< string, set< int >> mpTitle, mpAuthor, mpKey, mpPub, mpYear;
for ( int i= 0 ; i< n; i++ )
{
scanf ( "%d" , & id) ;
char c = getchar ( ) ;
getline ( cin, title) ;
mpTitle[ title] . insert ( id) ;
getline ( cin, author) ;
mpAuthor[ author] . insert ( id) ;
while ( cin >> key)
{
mpKey[ key] . insert ( id) ;
c = getchar ( ) ;
if ( c == '\n' ) break ;
}
getline ( cin, pub) ;
mpPub[ pub] . insert ( id) ;
getline ( cin, year) ;
mpYear[ year] . insert ( id) ;
}
string searchKey;
scanf ( "%d" , & m) ;
for ( int i= 0 ; i< m; i++ )
{
scanf ( "%d: " , & type) ;
getline ( cin, searchKey) ;
cout << type << ": " << searchKey << endl;
if ( type == 1 ) query ( mpTitle, searchKey) ;
else if ( type== 2 ) query ( mpAuthor, searchKey) ;
else if ( type== 3 ) query ( mpKey, searchKey) ;
else if ( type== 4 ) query ( mpPub, searchKey) ;
else query ( mpYear, searchKey) ;
}
return 0 ;
}
学习代码
知识点小结
void query ( map< string, set< int >> & mp, string& str) { }
for ( set< int > : : iterator it= mp[ str] . begin ( ) ; it!= mp[ str] . end ( ) ; it++ )
if ( mp. find ( str) == mp. end ( ) )