#P16653. [GKS 2018 #F] Common Anagrams

[GKS 2018 #F] Common Anagrams

Problem Description

Ayla has two strings AA and BB, each of length LL, and each of which is made of uppercase English alphabet letters. She would like to know how many different substrings of AA appear as anagrammatic substrings of BB. More formally, she wants the number of different ordered tuples (i,j)(i, j), with 0ij<L0 \le i \le j < L, such that the ii-th through jj-th characters of AA (inclusive) are the same multiset of characters as at least one contiguous substring of length (ji+1)(j - i + 1) in BB.

Input Format

The first line of the input gives the number of test cases, TT. TT test cases follow. Each test case starts with one line, containing LL: the length of the string. The next two lines contain one string of LL characters each: these are strings AA and BB, in that order.

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 the answer Ayla wants, as described above.

6
3
ABB
BAB
3
BAB
ABB
6
CATYYY
XXXTAC
9
SUBXXXXXX
SUBBUSUSB
4
AAAA
AAAA
19
PLEASEHELPIMTRAPPED
INAKICKSTARTFACTORY
Case #1: 5
Case #2: 6
Case #3: 6
Case #4: 6
Case #5: 10
Case #6: 9

Hint

In Sample Case #1, L=3L = 3, AA = ABB, and BB = BAB There are 6 substrings of AA:

  • A. The substring A in BB is (trivially) an anagram.
  • B. The substring B in BB is (trivially) an anagram.
  • B. The substring B in BB is (trivially) an anagram.
  • AB. The substring AB in BB is (trivially) an anagram.
  • BB. There is no corresponding anagrammatic substring in BB.
  • ABB. The substring BAB in BB is an anagram.

In total, there are 5 substrings with a corresponding anagrammatic substring in BB, so the answer is 5.

In Sample Case #2, note that it is the same as Sample Case #1, except that AA and BB are swapped. This changes the answer to 6!

In Sample Case #3, note that the substring CAT in AA has the corresponding substring TAC in BB which is an anagram. This still counts, even though the strings are at different indices in their respective strings.

In Sample Case #4, note that although the substring SUB in AA has several corresponding substrings in BB which are anagrams, it only counts once.

In Sample Case #5, note that every substring of AA has a corresponding anagrammatic substring in BB, so the answer is 10.

Limits

1T1001 \le T \le 100.

1L501 \le L \le 50.

Small dataset (Test set 1 - Visible)

The two strings AA and BB will consist only of the characters A and B.

Large dataset (Test set 2 - Hidden)

No additional constraints.