解法一:倒排索引
遍历全部Book查找会非常慢,使用 Map
在单词和书本 id
之间建立倒排索引加速查找。
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
int N = Integer.parseInt(in.readLine());
Map<String, List<String>> titieMap = new HashMap<>();
Map<String, List<String>> authorMap = new HashMap<>();
Map<String, List<String>> keyWordMap = new HashMap<>();
Map<String, List<String>> publisherMap = new HashMap<>();
Map<Integer, List<String>> yearMap = new HashMap<>();
Book[] books = new Book[N];
for (int i = 0; i < N; ++i) {
books[i] = new Book(
in.readLine(),
in.readLine(),
in.readLine(),
in.readLine(),
in.readLine(),
Integer.parseInt(in.readLine())
);
}
Arrays.sort(books);
List<String> tmp;
for (Book book : books) {
tmp = titieMap.getOrDefault(book.title, new ArrayList<>());
tmp.add(book.id);
titieMap.put(book.title, tmp);
tmp = authorMap.getOrDefault(book.author, new ArrayList<>());
tmp.add(book.id);
authorMap.put(book.author, tmp);
for (String keyword : book.keyWords) {
tmp = keyWordMap.getOrDefault(keyword, new ArrayList<>());
tmp.add(book.id);
keyWordMap.put(keyword, tmp);
}
tmp = publisherMap.getOrDefault(book.publisher, new ArrayList<>());
tmp.add(book.id);
publisherMap.put(book.publisher, tmp);
tmp = yearMap.getOrDefault(book.year, new ArrayList<>());
tmp.add(book.id);
yearMap.put(book.year, tmp);
}
int M = Integer.parseInt(in.readLine());
for (int i = 0; i < M; ++i) {
String query = in.readLine();
out.println(query);
String request = query.substring(3);
List<String> ans;
switch (query.charAt(0)) {
case '1':
ans = titieMap.get(request);
break;
case '2':
ans = authorMap.get(request);
break;
case '3':
ans = keyWordMap.get(request);
break;
case '4':
ans = publisherMap.get(request);
break;
case '5':
ans = yearMap.get(Integer.parseInt(request));
break;
default:
ans = null;
}
if (ans == null) {
out.println("Not Found");
} else {
for (String s : ans) {
out.println(s);
}
}
}
out.flush();
}
}
class Book implements Comparable {
String id;
String title;
String author;
Set<String> keyWords;
String publisher;
int year;
Book(String id, String title, String author, String keyWords, String publisher, int year) {
this.id = id;
this.title = title;
this.author = author;
this.keyWords = new HashSet<>(Arrays.asList(keyWords.split(" ")));
this.publisher = publisher;
this.year = year;
}
@Override
public String toString() {
return "Book{" +
"id=" + id +
", title='" + title + '\'' +
", author='" + author + '\'' +
", keyWords=" + keyWords +
", publisher='" + publisher + '\'' +
", year=" + year +
'}';
}
@Override
public int compareTo(Object o) {
Book book = (Book) o;
return id.compareTo(book.id);
}
}