#C13799. Top N Frequent Words

    ID: 43376 Type: Default 1000ms 256MiB

Top N Frequent Words

Top N Frequent Words

Given a string text and an integer n, your task is to find the top n most frequently occurring words in text.

The words should be compared case-sensitively and are separated by spaces. In the case where multiple words have the same frequency, the word that appears first in the input should be ranked higher.

For example, if text is "this is a test this is only a test" and n is 2, the output should be "this is" since "this" and "is" are the most frequent words (frequency = 2) and "this" appears before "is" in the original text.

The frequency ranking can be expressed mathematically as follows: For each word \(w\), let \(f(w)\) be its count in the string. Then the sorting key for a word \(w\) is \((-f(w), i(w))\), where \(i(w)\) is the index of the first occurrence of \(w\) in the list of words. The goal is to output the first n words of the sorted order.

inputFormat

The input is read from standard input (stdin) and consists of two lines:

  1. The first line contains the string text.
  2. The second line contains an integer n.

outputFormat

Output the top n words separated by a single space to the standard output (stdout).

## sample
this is a test this is only a test
2
this is