Sanghak Language
Time limit1sMemory limit128 MB
Count the distinct strings formed by concatenating any nonempty prefix of a Namgyu word with any nonempty suffix of a Jaehyeok word, summing over several test cases.
- Level
Hard8 of 10
- Topics
- Trie, String, Combinatorics, Prefix sum
- Solved
- No attempts yet
Problem
Long ago there were two languages, Namgyu and Jaehyeok. At some point a language halfway between them, called Sanghak, came into being.
A Sanghak word is built as follows.
- Pick one Namgyu word and choose one of its prefixes of length at least (a piece cut from the front).
- Pick one Jaehyeok word and choose one of its suffixes of length at least (a piece cut from the back).
- Concatenate the suffix right after the prefix. The order is always the Namgyu prefix followed by the Jaehyeok suffix.
For example, from the Namgyu word abc and the Jaehyeok word de you can make ae, ade, abe, abde, abce, and abcde, but you cannot make bce, ace, or abc.
It does not matter whether the resulting word actually means anything. Given a Namgyu dictionary and a Jaehyeok dictionary, determine how many distinct Sanghak words can be formed. For instance, with Namgyu words ab, abc and Jaehyeok words cd, d, the word abcd can be formed in two different ways, but since it is the same word it is counted only once.
Input
The input consists of several test cases and ends with a line 0 0.
The first line of each test case contains the number of Namgyu words and the number of Jaehyeok words . ()
The next lines each contain one Namgyu word, and the following lines each contain one Jaehyeok word. Every word consists of between and lowercase English letters. No word appears twice within the same language, and the total length of all words in one language is at most .
Output
For each test case, print on its own line the number of distinct Sanghak words that can be formed.