K - Strings

4

5 votes
String, aho corasick, auxiliary tree, Algorithms, Medium-Hard, Depth-first search, Approved
Problem

You are given a list L of N distinct strings, where each string is denoted by si.

For two strings a and b, define a function,

                F(a, b) =  1   if a is suffix of b
                          0   otherwise

For a given list of strings X and any string s X ,
Define a function,

G(s, X) = yX F(s, y)

Your task is to answer Q queries. In ith query you are given ki indices, where each index denotes the index of the respective string in the given list L. Let T denote the list of strings given in the query. Then, output the maximum value of G(s, T) sT.

Input :

First line contains two integers N and Q. The next N lines each contain a single string si belonging to list L. This is followed by Q lines, with the ith line denoting the ith query. Each query starts with an integer ki followed by ki integers denoting the indices of strings in this query.

Output :

For every query output a single integer denoting the maximum value of G.

Constraints :

1N,Q105

i|si|106

i|ki|106

Note: All string contain only lowercase English alphabet.

Time Limit: 2
Memory Limit: 512
Source Limit:
Explanation

Query 1:

 T = { "banana", "anana", "nana", "akela" }
 G("banana", T) = 1
 G("anana", T)  = 2
 G("nana", T)   = 3     (Maximum value)
 G("akela", T)  = 1,

Query 2:

 T = { "banana", "nana", "kela" }
 G("banana", T) = 1
 G("nana", T)   = 2     (Maximum value)
 G("kela", T)   = 1

Query 3:

 T = { "banana", "akela", "kela" }
 G("banana", T) = 1
 G("akela", T)  = 1     
 G("kela", T)   = 2    (Maximum value)
Editor Image

?