CYCLINGS - Distinct Cyclings

The Kingdom of Gridland contains P provinces. Each province is defined as a 2 x N grid where each cell in the grid represents a city. Every cell in the grid contains a single lowercase character denoting the first character of the city name corresponding to that cell.

From a city with the coordinates (i, j), it is possible to move to any of the following cells in unit of time, provided that the destination cell is inside the grid:

  • (i + 1, j)
  • (i, j + 1)
  • (i - 1, j)
  • (i, j - 1)

A knight wants to visit all the cities in Gridland. He can start his journey in any city and immediately stops his journey after having visited each city at least once. Moreover, he always plans his journey in such a way that the total time required to complete it is minimum.

After completing his tour of each province, the knight forms a string by concatenating the characters of all the cells in his path. How many distinct strings can he form in each province?

Input

The first line contains a single integer P, denoting the number of provinces. The 3 * P subsequent lines describe each province. The first line contains an integer N, denoting the number of columns in the province. Each of the next two lines contains a string S, of length N and consisting of only lowercase letters denoting the characters for the first and second row of the province.

Constraints

  • 1 ≤ P ≤ 15
  • 1 ≤ N ≤ 600
  • Output

    For each province, print the number of distinct strings the knight can form on a new line.

    Sample Input

    3
    1
    a
    a
    3
    dab
    abd
    5
    ababa
    babab
    

    Sample Output

    1
    8
    2
    

    Explanation

    For the second province, here are all possible unique strings that can be formed: abdbad, adabdb, badabd, bdbada, dababd, dabdba, dbabad, and dbadab.

    Reference

    HackerRank - Gridland Provinces

    Added by:sgtlaugh
    Date:2021-03-27
    Time limit:3s
    Source limit:50000B
    Memory limit:1536MB
    Cluster: Cube (Intel G860)
    Languages:All
    Resource:Own problem, used in HackerRank

    hide comments
    2022-09-04 13:49:25 majid
    Does answer fit in 64 bit Integer?
    © Spoj.com. All Rights Reserved. Spoj uses Sphere Engine™ © by Sphere Research Labs.