1、知识点:字符串比较、排序
2、思路:题目要求结果按照图书编号顺序输出,因此要先将图书排序,然后将搜索词分类比较即可。注意:结构体可以直接赋值,无需重载赋值运算符。
/*用途:
**说明:
**算法:
*/
//#define LOCAL
#include <vector>
#include <cstdio>
#include <string.h>
#include <algorithm>
using namespace std;
struct book{
char id[10];
char title[100];
char author[100];
char key[5][15];
char publisher[100];
char year[10];
int key_num;
};
vector<book> vec_bo;
vector<int> vec_id;
int N, M;
void to_keywords(book &b, char* s);
bool cmp_id(book b1, book b2);
void query_book(char* s, int type);
bool cmp_keywords(char*s, int ind);
int main()
{
#ifdef LOCAL
freopen("1022_Digital_Library.in", "r", stdin);
freopen("1022_Digital_Library.out", "w", stdout);
#endif
scanf("%d", &N);
vec_bo.resize(N);
getchar(); //读取换行符
char buf[100];
book b;
for(int i=0; i<N; i++){
gets(b.id);
gets(b.title);
gets(b.author);
gets(buf); //提取关键字一行
to_keywords(b, buf); //分割关键字
gets(b.publisher);
gets(b.year);
vec_bo.at(i) = b;
}
sort(vec_bo.begin(), vec_bo.end(), cmp_id);
scanf("%d", &M);
for(int i=0; i<M; i++){
int type;
char query[100];
scanf("%d: ", &type);
gets(query);
printf("%d: %s\n", type, query);
query_book(query, type);
int num = vec_id.size();
for(int j=0; j<num; j++)
printf("%s\n", vec_bo.at(vec_id.at(j)).id);
if(!num)
printf("Not Found\n");
}
return 0;
}
void to_keywords(book &b, char* s)
{
char *res = strtok(s, " ");
b.key_num = 0;
while(res){
strcpy(b.key[b.key_num++], res);
res = strtok(NULL, " ");
}
}
bool cmp_id(book b1, book b2)
{
return (strcmp(b1.id, b2.id) <= 0 ? 1 : 0);
}
void query_book(char* s, int type)
{
vec_id.clear();
for(int i=0; i<N; i++){
switch(type){
case(1):
if(!strcmp(s, vec_bo.at(i).id)){
vec_id.push_back(i);
break;
}
case(2):
if(!strcmp(s, vec_bo.at(i).title)){
vec_id.push_back(i);
break;
}
case(3):
if(!strcmp(s, vec_bo.at(i).author)){
vec_id.push_back(i);
break;
}
case(4):
if(cmp_keywords(s, i)){
vec_id.push_back(i);
break;
}
case(5):
if(!strcmp(s, vec_bo.at(i).publisher)){
vec_id.push_back(i);
break;
}
case(6):
if(!strcmp(s, vec_bo.at(i).year)){
vec_id.push_back(i);
break;
}
default:
break;
}
}
}
bool cmp_keywords(char*s, int ind)
{
int num = vec_bo.at(ind).key_num;
for(int i=0; i<num; i++){
if(!strcmp(s, vec_bo.at(ind).key[i])){
return 1;
}
}
return 0;
}