Created
June 15, 2020 12:46
-
-
Save mloza/e30579725a28d28a02f67af4f93fbdb5 to your computer and use it in GitHub Desktop.
GTE
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class TitleSearch { | |
public static void main(String[] args) { | |
final Scanner sc = new Scanner(System.in); | |
List<String> titles = new ArrayList<>(); | |
final int n = sc.nextInt(); | |
sc.nextLine(); | |
for (int i = 0; i < n; ++i) { | |
titles.add(sc.nextLine()); | |
} | |
List<String> queries = new ArrayList<>(); | |
final int q = sc.nextInt(); | |
sc.nextLine(); | |
for (int i = 0; i < q; ++i) { | |
queries.add(sc.nextLine()); | |
} | |
solve(titles, queries); | |
} | |
static void solve(List<String> titles, List<String> queries) { | |
Map<String, List<HashSet<String>>> tr = new HashMap<>(); | |
for (String title : titles) { | |
String[] keywordsArr = title.toLowerCase().split(" "); | |
HashSet<String> keywordsSet = new HashSet<>(Arrays.asList(keywordsArr)); | |
keywordsArr = null; | |
// List to handle duplicated titles | |
tr.computeIfAbsent(title, t -> new ArrayList<>()).add(keywordsSet); | |
} | |
PriorityQueue<String> results = new PriorityQueue<>((a, b) -> { | |
int result = a.split(" ").length - b.split(" ").length; | |
if (result == 0) { | |
return a.compareTo(b); | |
} | |
return result; | |
}); | |
for (String query : queries) { | |
String[] keywordsArr = query.toLowerCase().split(" "); | |
TreeSet<String> keywordsSet = new TreeSet<>(); | |
for (int i = 0; i < keywordsArr.length; i++) { | |
keywordsSet.add(keywordsArr[i]); | |
} | |
keywordsArr = null; | |
tr.forEach((i, k) -> { | |
k.forEach(t -> { | |
if (t.containsAll(keywordsSet)) { | |
results.add(i); | |
} | |
}); | |
}); | |
System.out.println(Math.min(10, results.size())); | |
for (int i = 0; i < 10; i++) { | |
String title = results.poll(); | |
if (title == null) break; | |
System.out.println(title); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment