#K86202. Form the Longest Word
Form the Longest Word
Form the Longest Word
Given a set of letters (called a rack) and a dictionary of words, your task is to determine the longest word(s) from the dictionary that can be formed using the letters in the rack. A letter in the rack can be used at most as many times as it appears. If more than one word of maximum length can be formed, output them in lexicographical order separated by a single space. The solution should read input from standard input (stdin) and print the result to standard output (stdout).
Mathematically, if the rack is represented by a multiset ( R ) and a word ( w ) is represented by its letter multiset ( W ), then the word is valid if and only if ( W \subseteq R ). Among all valid words, let ( L = \max{ |w| : w ; is ; valid } ). You are to output all valid words of length ( L ) in lexicographical order.
inputFormat
The input is read from standard input and has the following format:
- The first line contains an integer ( n ) (( 0 \le n \le 10^5 )), representing the number of letters in the rack.
- The second line contains ( n ) lowercase letters separated by spaces. If ( n = 0 ), this line will be empty.
- The third line contains an integer ( m ) (( 0 \le m \le 10^5 )), representing the number of words in the dictionary.
- The following ( m ) lines each contain a word composed of lowercase letters.
outputFormat
Print to standard output a single line containing the longest valid word(s) that can be formed from the rack. If there are multiple words of maximum length, output them in lexicographical order, separated by a single space. If no valid word can be formed, output an empty line.## sample
5
a e l p p
4
pale
leap
plea
apple
apple
</p>