Restaurant Reviews

Hard

A restaurant listing website has asked you to analyse the reviews on its restaurants.
The reviews need to be sorted by how good they are, the best reviews go on top. The goodness a review is determined by the number of times "good words" appear in them. You are given a list of good words.

Given n reviews and m good words, sort the reviews, such that the one with most good words appears first. For reviews with the same number of good words, maintain the initial order.

Examples:
Reviews: ["good restaurant", "tasty food nice ambience", "nice place"]
Good Words: ["good", "lovely", "nice", "tasty"]
Output: ["tasty food nice ambience", "good restaurant", "nice place"]

Testing

Input Format

The input contains the following lines:

  • Two space-separated integers ‘n’ and ‘m’ denoting the number of reviews and good words respectively.
  • n lines, each containing a review.
  • A line with m space-separated words, denoting the good words.

Output format

The output has n lines, each containing a review. The reviews are sorted as required.

Sample Input

3 4
good restaurant
tasty food nice ambience
nice place
good lovely nice tasty

Expected Output

tasty food nice ambience
good restaurant
nice place

Constraints

1 <= n <= 200
1 <= m <= 10000
1 <= review length <= 7000
1 <= word length <= 6
Words have only lower-case characters (a-z).

Companies
Editorial Link: Editorial