#K65382. Longest String with Required Characters
Longest String with Required Characters
Longest String with Required Characters
Given a list of n strings and q queries, your task is to find, for each query, the length of the longest string which contains all of the required characters specified in that query. Formally, for each query with a set of characters Q, you need to find a string s from the list such that every character in Q appears in s. If there are multiple valid strings, output the one with the maximum length. If no string satisfies the condition, output -1.
For example, consider a query where Q = {a, p}. A string like "apple" contains both 'a' and 'p', and if it is the longest among those satisfying the condition, its length (which is 5) should be the answer for that query.
Mathematically, for a query with required characters Q, you must compute [ \text{answer} = \max_{s \in S} {|s| : Q \subseteq {c : c \text{ is a character in } s}} ] where S is the set of strings provided as input. If no such s exists, answer is -1.
inputFormat
The input is given via standard input (stdin) and consists of:
- A line containing two space-separated integers n and q, where n is the number of strings and q is the number of queries.
- n lines each containing a string.
- q lines each containing a query. Each query is composed of an integer k and a string of k characters, separated by a space. (Note: k indicates the number of characters but is not needed in your logic as the string already provides its characters.)
outputFormat
For each query, print a single integer on a new line representing the length of the longest string that contains all of the required characters. If no string matches the query conditions, output -1.
## sample5 3
apple
banana
cherry
date
elderberry
2 ap
3 ble
1 c
5
10
6
</p>