1022. Digital Library (30)

链接:http://pat.zju.edu.cn/contests/pat-a-practise/1022

 

题意:给定 N (<=10000) 本书的信息,包括 7 位 ID,最多 80 字符的书名,最多 80 字符的作者名, 多个最多 10 字符的关键词,最多 80 字符的出版商和属于 [1000, 3000]的出版时间。 另给出 M (<=1000) 的查询请求,按照查询格式分为:

1: 书名

2: 作者

3: 关键词

4: 出版商

5: 年份

 

分析:其他属性排序后遍历查询即可,关键词合理的方法应该建立倒排索引,这里用vector水过了。。

 

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<vector>
#include<string>

using namespace std;

typedef struct Book {
	int id;
	char title[85];
	char author[85];
	vector<string> keywords;
	char publisher[85];
	char year[10];

} Book;

Book book[10005];

int cmp(const void*a, const void*b) {
	Book* aa = (Book*) a;
	Book* bb = (Book*) b;
	return aa->id - bb->id;

}

int main() {
//	freopen("in.txt", "r", stdin);
	int n;
	scanf("%d", &n);
	int i;
	char keyword[15];
	for (i = 0; i < n; i++) {
		scanf("%d", &book[i].id);
		getchar();
		gets(book[i].title);
		gets(book[i].author);

		char ch;
		while (scanf("%s", keyword)) {
			string s = keyword;
			book[i].keywords.push_back(s);
			ch = getchar();
			if (ch == '\n')
				break;
		}

		gets(book[i].publisher);
		scanf("%s", book[i].year);

	}
	qsort(book, n, sizeof(Book), cmp);

	int m;
	scanf("%d", &m);
	getchar();
	char query[100];
	while (m--) {
		int found = 0;
		gets(query);
		printf("%s\n", query);
		if (query[0] == '1') {
			for (i = 0; i < n; i++) {
				if (strcmp(book[i].title, &query[3]) == 0) {
					printf("%07d\n", book[i].id);
					found = 1;
				}
			}
		} else if (query[0] == '2') {
			for (i = 0; i < n; i++) {
				if (strcmp(book[i].author, &query[3]) == 0) {
					printf("%07d\n", book[i].id);
					found = 1;
				}
			}
		} else if (query[0] == '3') {
			int j;
			for (i = 0; i < n; i++) {
				for (j = 0; j < book[i].keywords.size(); j++)
					if (strcmp(book[i].keywords[j].c_str(), &query[3]) == 0) {
						printf("%07d\n", book[i].id);
						found = 1;
					}
			}

		} else if (query[0] == '4') {
			for (i = 0; i < n; i++) {
				if (strcmp(book[i].publisher, &query[3]) == 0) {
					printf("%07d\n", book[i].id);
					found = 1;
				}
			}
		} else {
			for (i = 0; i < n; i++) {
				if (strcmp(book[i].year, &query[3]) == 0) {
					printf("%07d\n", book[i].id);
					found = 1;
				}
			}

		}
		if(!found)
			printf("Not Found\n");

	}

	return 0;
}

 

 

你可能感兴趣的:(library)