#P16778. [GKS 2020 #H] Friends

[GKS 2020 #H] Friends

Problem Description

There are NN people in the world numbered 11 to NN. The ii-th person has a distinct name SiS_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 nn between person AA and person BB is a sequence of people X1,X2,...,XnX_1, X_2, ..., X_n such that X1=AX_1 = A, Xn=BX_n = B, and XiX_i and Xi+1X_{i+1} are friends, for i=1i=1 to n1n-1. Note that any two people can have zero or more friendship chains between them.

For each of the given QQ 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-1.

Input Format

The first line of the input gives the number of test cases, TT. TT test cases follow. The first line of each test case contains the two integers NN and QQ. The second line contains NN strings, which are people's names. The ii-th string (starting from 11) is SiS_i. Then, QQ lines follow, describing the queries. The ii-th of these lines contains the two integers XiX_i and YiY_i, which are the indexes (counting starting from 11) of a pair of people in the list of names.

Output Format

For each test case, output one line containing Case #x\#x: yy, where xx is the test case number (starting from 11) and yy is a list of the answers for the QQ queries in order, separated by spaces.

2
5 2
LIZZIE KEVIN BOHDAN LALIT RUOYU
1 2
1 3
2 2
KICK START
1 2
1 2
Case #1: 2 3
Case #2: -1 -1

Hint

In Sample Case #11, there are 22 queries:

  • In the 11st query, LIZZIE and KEVIN are friends (because they share the letter E in their names). So, the shortest friendship chain length is 22.
  • In the 22nd query, LIZZIE and BOHDAN are not friends, but have 22 possible shortest friendship chains (either via KEVIN or LALIT). So, the shortest friendship chain length is 33. Note that there are other friendship chains as well, but they are longer.

In Sample Case #22, there are 22 queries:

  • In the 11st query, KICK and START are not connected by a chain of friends.
  • The 22nd query is the same as the 11st query. Note that queries are not guaranteed to be distinct.

Limits

1T1001 \le T \le 100.

1Q5×1041 \le Q \le 5 \times 10^4.

SiS_i consists of uppercase English letters, for all ii.

1length of Si201 \le \text{length of } S_i \le 20, for all ii.

All SiS_i are distinct.

1Xi<YiN1 \le X_i < Y_i \le N, for all ii.

Test Set 11

2N1002 \le N \le 100.

Test Set 22

103<N5×10410^3 < N \le 5 \times 10^4 in at most 1010 cases.

2N1032 \le N \le 10^3 in all other cases.