#K35722. Longest Combined Gemstone

    ID: 25595 Type: Default 1000ms 256MiB

Longest Combined Gemstone

Longest Combined Gemstone

You are given two collections of gemstones. Each gemstone is represented as a string consisting of lowercase letters. Your task is to choose one gemstone from each collection and concatenate them to form a new gemstone. The resulting gemstone is valid if it does not contain any repeated characters. In other words, for two chosen gemstones gem1 and gem2, the concatenation is valid if

$$|\{\text{characters in } gem1\} \cup \{\text{characters in } gem2\}| = |gem1| + |gem2|. $$

Your goal is to find the maximum possible length of a valid gemstone formed by such a combination. If no valid combination exists, output -1.

inputFormat

The first line of the input contains two integers (n) and (m), representing the number of gemstones in the first and second collection, respectively. The next (n) lines each contain a non-empty string denoting a gemstone from the first collection. This is followed by (m) lines, where each line contains a gemstone from the second collection.

outputFormat

Output a single integer which is the length of the longest valid gemstone that can be formed by combining one gemstone from the first collection and one from the second collection. If no valid combination exists, output -1.## sample

3 3
ab
cd
efg
hij
klm
nop
6