P16778 [GKS 2020 #H] Friends
Description
There are $N$ people in the world numbered $1$ to $N$. The $i$-th person has a distinct name $S_i$ that is a string of uppercase English letters.
Two people are friends if and only if there is some letter that appears at least once in each of their names. Any such letter does not need to be at the same position in both names. After all, friendship requires having something in common!
A friendship chain of length $n$ between person $A$ and person $B$ is a sequence of people $X_1, X_2, ..., X_n$ such that $X_1 = A$, $X_n = B$, and $X_i$ and $X_{i+1}$ are friends, for $i=1$ to $n-1$. Note that any two people can have zero or more friendship chains between them.
For each of the given $Q$ pairs of people, can you find the length of the shortest friendship chain between them? If there is no friendship chain between a pair, output $-1$.
Input Format
The first line of the input gives the number of test cases, $T$. $T$ test cases follow. The first line of each test case contains the two integers $N$ and $Q$. The second line contains $N$ strings, which are people's names. The $i$-th string (starting from $1$) is $S_i$. Then, $Q$ lines follow, describing the queries. The $i$-th of these lines contains the two integers $X_i$ and $Y_i$, which are the indexes (counting starting from $1$) of a pair of people in the list of names.
Output Format
For each test case, output one line containing Case $\#x$: $y$, where $x$ is the test case number (starting from $1$) and $y$ is a list of the answers for the $Q$ queries in order, separated by spaces.
Explanation/Hint
In Sample Case #$1$, there are $2$ queries:
- In the $1$st query, LIZZIE and KEVIN are friends (because they share the letter E in their names). So, the shortest friendship chain length is $2$.
- In the $2$nd query, LIZZIE and BOHDAN are not friends, but have $2$ possible shortest friendship chains (either via KEVIN or LALIT). So, the shortest friendship chain length is $3$. Note that there are other friendship chains as well, but they are longer.
In Sample Case #$2$, there are $2$ queries:
- In the $1$st query, KICK and START are not connected by a chain of friends.
- The $2$nd query is the same as the $1$st query. Note that queries are not guaranteed to be distinct.
### Limits
$1 \le T \le 100$.
$1 \le Q \le 5 \times 10^4$.
$S_i$ consists of uppercase English letters, for all $i$.
$1 \le \text{length of } S_i \le 20$, for all $i$.
All $S_i$ are distinct.
$1 \le X_i < Y_i \le N$, for all $i$.
**Test Set $1$**
$2 \le N \le 100$.
**Test Set $2$**
$10^3 < N \le 5 \times 10^4$ in at most $10$ cases.
$2 \le N \le 10^3$ in all other cases.