#K72212. Can Form Words
Can Form Words
Can Form Words
You are given a list of words and a list of individual letters. Your task is to process the words in the given order and, for each word, check if it can be completely formed using the available letters. If a word can be formed, append it to the result and consume the letters used from the list. Otherwise, move on to the next word.
Details:
- For a word to be formed, each of its characters must be present in the remaining letters in at least the same frequency.
- Once a word is selected, the letters used to form it are deducted from the available list, and cannot be reused.
The answer should be output as a list of words separated by a single space. If no word can be formed, output an empty line.
The problem can be formulated mathematically as follows:
Given two multisets \(W = [w_1, w_2, \dots, w_n]\) (words) and \(L\) (letters), for each word \(w_i\) with frequency count \(f_{w_i}(c)\) for each character \(c\), if \(f_{w_i}(c) \le f_L(c)\) for all characters \(c\) then append \(w_i\) to the result and update \(f_L(c) := f_L(c) - f_{w_i}(c)\).
inputFormat
The input is read from standard input (stdin) in the following format:
- An integer \(n\) denoting the number of words.
- The next \(n\) lines each contain a single word.
- An integer \(m\) denoting the number of letters.
- A single line containing \(m\) space-separated lowercase letters.
outputFormat
Output the successfully formed words in the order they appear in the input, separated by a single space. If no words can be formed, output an empty line.
## sample4
apple
orange
pear
grape
20
a p p l e o r a n g e p e a r g r a p e
apple orange pear grape
</p>