We need to count number of submatrices (contiguous in rows and columns) such that we can rearrange characters in each row independently (i.e., we can permute the characters within that row, but only within the row, not across rows) to make all rows and columns palindromes.
Interpretation: For a submatrix defined by rows i1..i2 and columns j1..j2. We can reorder each row arbitrarily. After reordering, we need that each row (the string of length width = (j2 - j1 + 1)) is a palindrome, and each column (the string of height = (i2 - i1 + 1)) is a palindrome.
We can reorder rows individually, so essentially for each row we can choose any permutation of its entries. The requirement for rows: after reordering, each row is palindrome. That imposes constraints on the multiset of characters in that row (within the submatrix). For a string of length L to be rearrangeable into a palindrome, the necessary and sufficient condition is that at most one character appears an odd number of times (if L is even, then all counts must be even; if odd, exactly one odd count). So for each row, within the selected columns, the count of each character in that row segment must satisfy that parity condition.
Now after reordering rows to make them palindromes, we also need each column to be a palindrome. But note that we have already fixed the arrangement of characters in each row (by the reordering). However we have freedom to choose the reordering per row. So we need to see if there exists assignments of permutations to each row such that all columns also become palindromes.
This is reminiscent of constructing a matrix where rows are individually palindromic and columns are palindromic. Given the multisets of entries in each row, we need to assign actual positions.
But maybe the condition simplifies: Because we can rearrange each row arbitrarily, the ability to make all rows and columns palindromes is equivalent to certain parity constraints on the counts of characters in each row and each column? Let's think.
We have a submatrix of size R x C (R = i2-i1+1, C = j2-j1+1). We need to fill each row with the given multiset of characters (the segment). We can permute within row. Need each row palindrome: so row i must be symmetric about center: for each position j (1-indexed within the submatrix), the character at column j equals character at column C+1-j. That means the row assignment must pair up columns symmetrically.
Similarly, each column must be palindrome: for each row i, character at row i, column j equals character at row R+1-i, column j.
Essentially we need to assign characters to positions (i,j) with i∈[1,R], j∈[1,C] such that:
- For each row i, the multiset of characters in that row is fixed (the given segment).
- For each row i, the row is palindrome: a_{i,j} = a_{i, C+1-j}.
- For each column j, the column is palindrome: a_{i,j} = a_{R+1-i, j}.
These constraints link positions.
Let’s denote symmetric positions due to both row and column palindromicity. For a matrix with both row and column palindrome constraints, the positions are partitioned into equivalence classes defined by the symmetries: row reflection and column reflection.
Specifically, we have two involutions: r(i) = R+1-i (row flip), c(j) = C+1-j (column flip). The constraints are:
- a_{i,j} = a_{i, c(j)} (row palindrome)
- a_{i,j} = a_{r(i), j} (column palindrome)
Combining, we also get a_{i,j} = a_{r(i), c(j)} (by applying both). So the equivalence class of a position (i,j) includes (i,j), (i,c(j)), (r(i),j), (r(i),c(j)). However, some of these may be same if i = r(i) or j = c(j).
Thus the entire matrix can be partitioned into orbits under the group generated by row and column reflections (the Klein four group, unless there is symmetry). For each orbit, all positions must have the same character.
Given that we can assign characters arbitrarily subject to these equalities, and we also have row multiset constraints: For each row i, the multiset of characters in that row (over all j) must match the given segment's multiset.
Now the question reduces to: For a given submatrix (with given character segments per row), does there exist an assignment of characters to each equivalence class (i.e., to each cell) respecting these equalities, such that for each row i, the multiset of characters in that row (as determined by the classes) matches the given multiset? And we are free to assign within each class any character, but all positions in that class must be same.
This is a kind of feasibility problem. Since the input is small (n,m ≤ 250), total number of submatrices O(n^2 m^2) which could be up to (250^4) ≈ 3.9e9 too many. We need more clever counting.
We need to count number of submatrices satisfying the condition. Usually such problems can be solved by considering for each pair of columns, or using bitset/hashing for rows? Let's try to derive necessary and sufficient conditions that can be checked efficiently across ranges.
Observation: Because rows can be rearranged arbitrarily, the condition that each row can be made palindrome imposes that for each row, within the selected columns, the count of each character modulo 2 has at most 1 odd. But that's only row condition. Additionally we need column palindrome condition to be achievable.
But maybe the combined condition is equivalent to something like: For each pair of rows (i, r(i)) we need some compatibility, etc.
Let's analyze small cases to get insight.
Consider a submatrix of size R x C. For each row i, we have its multiset of characters from the original matrix (segment). Let's denote the count vector for row i: f_i[ch] = number of occurrences of character ch in that row's selected columns. Row i must satisfy: at most one ch has odd count (i.e., parity vector with at most one 1). So that's a necessary condition for each row.
Now, after we assign positions subject to symmetries, the row multiset will be some distribution of characters across equivalence classes. But maybe we can rephrase feasibility: Because we can rearrange rows arbitrarily, we are essentially free to assign characters to positions within each row as long as we respect the palindrome structure. However, we also have column palindrome constraints that link rows.
Let's think of constructing the matrix: Because rows must be palindromes, the columns are determined by the values on one half of the row, but also columns must be palindromes, which impose relations between rows.
Suppose we label columns from 1 to C. Row palindrome means that for each i, a_{i,j} = a_{i, C+1-j}. So we only need to specify values for columns j=1..⌈C/2⌉. Similarly, column palindrome means that for each j, a_{i,j} = a_{R+1-i, j}. So for the rows, we only need to specify for i=1..⌈R/2⌉. Combined, we only need to specify values for positions with i <= ceil(R/2) and j <= ceil(C/2) (the "fundamental block"). Then the rest of the matrix is determined by the symmetries.
Specifically:
For i from 1 to R, j from 1 to C:
-
If i <= R/2? Actually better: define i' = min(i, R+1-i) and j' = min(j, C+1-j). Then a_{i,j} = a_{i', j'} (by repeated symmetry). Check: apply row flip if i > R+1-i; then column flip if j > C+1-j. Indeed, the orbit collapses to a single "representative" (i0, j0) where i0 = min(i, r(i)), j0 = min(j, c(j)). But careful: If both flips are applied, we get to (i', j') as described. Since the constraints are a_{i,j} = a_{i, c(j)} = a_{r(i), j} = a_{r(i),c(j)}, all four coincide. So all positions in the orbit have the same character. The representative can be chosen as (min(i, r(i)), min(j, c(j))). So essentially the matrix is determined by a block of size (⌈R/2⌉) x (⌈C/2⌉). Each cell of this block corresponds to an orbit covering up to 4 positions (except on central rows/columns where orbits are smaller). More precisely:
-
If R is odd, there is a middle row i_mid = (R+1)/2 that is fixed under row flip (r(i)=i). Similarly for C odd, a middle column j_mid fixed under column flip.
-
Positions on that middle row and middle column may belong to orbits of size 2 or 1.
But overall, the entire matrix consists of orbits: For each representative (i0, j0) with i0 from 1 to ceil(R/2), j0 from 1 to ceil(C/2), the orbit size = (if i0 != r(i0) then 2 else 1) * (if j0 != c(j0) then 2 else 1). Actually careful: when both i0 and j0 are not fixed individually, the orbit contains 4 distinct positions (i0,j0), (i0,c(j0)), (r(i0),j0), (r(i0),c(j0)). If i0 is fixed (i.e., i0 = r(i0) occurs only when R odd and i0 = (R+1)/2) then orbit size halves: if only i0 fixed, then orbit consists of (i0,j0) and (i0, c(j0)) -> size 2. Similarly for j0 fixed. If both fixed, orbit size 1.
Thus, the total number of positions equals sum over orbits of size.
Now, the row i has a given multiset of characters. The row i contains all positions with that row index. Each position belongs to some orbit. So row i's characters are determined by the assignments to the orbits that intersect row i.
We can think of the assignment as: assign a character to each orbit (representative). Then for each row i, the multiset of characters in that row is the multiset of characters of orbits that have a cell in row i, counted with multiplicity equal to the number of cells in that orbit that lie in row i (which is either 1 or 2 depending if the orbit has two cells in that row? Actually consider an orbit: if it's not on a mirrored row, it has two cells in two rows: i0 and r(i0). But within a single row, an orbit contributes either 1 cell (if the orbit's row index equals i and the orbit's other row index is different) or possibly 2? Let's examine: For a given orbit with representative (i0,j0). The positions are:
- (i0, j0)
- (i0, c(j0)) if j0 != c(j0)
- (r(i0), j0) if i0 != r(i0)
- (r(i0), c(j0)) if both not fixed.
Now, consider row i0. In that row, the orbit contributes positions: (i0, j0) and if j0 != c(j0) then also (i0, c(j0)). So it contributes either 1 or 2 cells depending on whether j0 is on the mirror (i.e., j0 = c(j0) means it's the middle column if C odd). Similarly, row r(i0) gets the other cells.
So in a row, an orbit contributes either 1 or 2 cells.
Thus row i's total character set is determined by the assignments to orbits that have cells in that row, with multiplicities 1 or 2.
Given we can choose assignment to orbits arbitrarily (subject to the fixed row multisets), the question: Is there an assignment of characters to orbits such that for each row i, the multiset of characters from its cells (with multiplicities) matches the given multiset (the original segment)? The original segment is fixed (the characters we have from the original matrix, but we can reorder within row, so we can permute which character goes to which cell). So essentially we need to partition the multiset of characters of row i into contributions from the orbits that hit row i, with each orbit requiring either 1 or 2 copies of the assigned character (if it contributes 2 cells in that row) and the same character assigned to that orbit must also appear in the other row(s) that share the orbit (with multiplicities accordingly). So we have a system of equations linking rows.
This looks like a flow or matching problem. However, maybe there is a simpler combinatorial condition: Because we can independently reorder rows, perhaps the condition reduces to that for each column, the multiset of characters in that column (original, before rearrangement) can be rearranged into a palindrome? But we can't reorder columns; only rows can be reordered per row. So column characters are not directly under our control; they are determined by row rearrangements.
Alternative approach: Since we can permute each row arbitrarily, we can think of each row as providing a multiset of characters. We need to arrange these characters into a matrix that is symmetric both horizontally and vertically. This is essentially constructing a palindrome matrix from given row multisets. This is possible iff the row multisets satisfy certain parity and consistency conditions.
I recall known problem: "Sonya and Matrix Beauty" is known from Codeforces (CF 713C? Actually there is CF 1080E? Wait there is "Sonya and Matrix" but this is "Sonya and Matrix Beauty". I've seen this problem before. I think it's from Codeforces Round #495 (Div. 2) or something. The solution uses hashing and Manacher's algorithm for rows after precomputing parity conditions for substrings of columns. Or maybe it's different: There is Codeforces problem "1080E Sonya and Matrix Beauty". Actually, there is a problem titled "Sonya and Matrix Beauty" from Codeforces 1080E? Let's check memory: I recall a problem: "Sonya and Matrix Beauty" where you count submatrices such that each row can be rearranged to palindrome and each column can be rearranged to palindrome. Solution: For each pair of columns (left, right), compute for each row a mask of parity of counts of characters (26 bits) and then consider only rows where the mask has at most one set bit (i.e., row can be palindrome). Then treat each such row as a string of 26-bit masks and find palindromic subarrays (using Manacher) in the vertical direction? Actually I recall: For each fixed left and right columns, we have an array of rows where each row's segment (from left to right) is considered. For each row, we compute a 26-bit mask representing parity of counts of each character in that segment. For the submatrix to be beautiful, we need each row's mask to have at most one set bit (i.e., row can be rearranged into palindrome). Additionally, we need that after reordering rows? Wait, columns also need to be palindromes. However, after rows are reordered individually, columns must be palindromes. But we cannot reorder columns; we can only reorder within each row. The column palindrome condition imposes constraints across rows: The columns must read the same forwards and backwards after row reordering. But note: Because we can reorder characters within each row, we can also affect columns. The condition likely translates to that the multiset of rows (the masks) must be such that we can arrange them to form a palindrome vertically? Actually think: For columns to be palindromes, after we assign characters to positions according to both symmetries, we need that for each column, the string of characters down the column is a palindrome. That means that for each column j, the sequence of characters in rows 1..R must be symmetric: char at row i equals char at row R+1-i. This is a condition on the assignment across rows. Since we can reorder each row arbitrarily, we can effectively choose how to pair characters across rows.
Maybe we can view the matrix as a set of rows, each with a multiset of characters. We need to arrange characters into positions such that rows are palindromic (horizontal symmetry) and columns are palindromic (vertical symmetry). This is equivalent to requiring that the whole matrix can be rearranged into a matrix that is symmetric both horizontally and vertically, which is essentially a matrix that is a palindrome both row-wise and column-wise after row-specific permutations.
I suspect there's known solution: For each pair of columns (l, r), we create an array of length n where for each row we check if the substring from l to r can be rearranged into a palindrome (i.e., parity mask has at most 1 set bit). Then we need to count number of contiguous row intervals where the sequence of these row-masks is such that we can permute rows? Actually columns must be palindrome as well, which imposes that for the selected rows, the multiset of characters in each column, after row permutations, must be palindromic. But note that the row permutations are independent per row, and they can also affect columns. However, maybe the condition reduces to that the multiset of rows (the row masks) must be such that the overall count of each character across all rows (considering the whole submatrix) is even except possibly for one? Let's test with examples.
Consider a submatrix of size R x C. If we have both row and column palindrome, what can we say about the multiset of all characters in the submatrix? For a palindrome matrix, each orbit (of size 1,2,4) must have all same character. Thus, the total count of each character must be divisible by something? Actually, if we sum over all orbits, the total count for each character is sum over orbits of (orbit size) if that character assigned to that orbit. But we can assign arbitrarily, so given the row multisets, is there a necessary condition about the parity of total counts per character? Let's derive.
Let’s denote for each row i, we have its segment multiset. If we sum the counts of a character across all rows, we get the total count of that character in the submatrix. For the matrix to be palindrome both ways, the total count of each character modulo 2 might be restricted. For example, consider a single cell (1x1). That's automatically palindrome. Here total count per character can be 1 (odd). For a 1x2 matrix (R=1, C=2). Row must be palindrome, so both cells must be same character. So total count of that character is 2 (even). For a 2x1 matrix: column must be palindrome, so both cells must be same character, total even. For 2x2 matrix: Both rows palindrome: each row has two cells that must be equal? Actually row palindrome: for each row, the two cells must be equal, so row i: a_i1 = a_i2. Column palindrome: a_11 = a_21, a_12 = a_22. So all four cells must be equal. So total count is 4 (even). For a 2x3 matrix: R=2, C=3. Row palindrome: each row length 3, so must have a pattern like X Y X. Column palindrome: a_1j = a_2j. So essentially the two rows are identical, and each row is symmetric. So the whole matrix is determined by the first half of first row and the middle column. The middle column cells must be equal across rows: a_1,2 = a_2,2. So essentially, the matrix has symmetry: a_1,1 = a_1,3 = a_2,1 = a_2,3, and a_1,2 = a_2,2. So total counts: for any character, it appears in multiples of 4 for the corners (since there are 4 corners) and multiples of 2 for the middle column. So overall counts: total for each character is even? Corners contribute 4 each, middle contributes 2 each, so yes, total count of each character is even. For a 3x3 matrix: R=3, C=3. Orbits: center (size 1), edges (positions (1,2),(3,2),(2,1),(2,3) but need to compute: Let's list orbits under D2 symmetry. Representatives:
- (1,1): orbit includes (1,1),(1,3),(3,1),(3,3) -> size 4.
- (1,2): includes (1,2),(3,2) -> size 2 (since column 2 is middle, row not fixed? Actually (1,2) row flip gives (3,2), column flip gives (1,2) because column 2 is middle, so only row flip matters).
- (2,1): includes (2,1),(2,3) -> size 2.
- (2,2): center alone size 1.
Thus total counts: corners: 4 each, top/bottom middle: 2 each, left/right middle: 2 each, center:1. So possible total counts per character can be odd (if assigned to center). So parity constraint: only at most one character can have odd total count? Since center can hold only one character, and all other orbits have even size, the sum of counts for a character is even unless it occupies the center orbit. So total counts mod 2: Exactly one character can have odd count if R and C are both odd? If either dimension even, all orbits have even size? Let's see: If R even, then there is no middle row, so all orbits have size multiple of 2? Check R=2, C=2: all orbits size 4? Actually representatives: (1,1): orbit (1,1),(1,2),(2,1),(2,2) -> size 4. So all even. R=2, C=3: R even, C odd: Orbits: for columns: middle column j=2 is fixed? Actually C odd, so there is middle column. R even, no middle row. Orbits: (1,1) -> (1,1),(1,3),(2,1),(2,3) size 4. (1,2) -> (1,2),(2,2) size 2. So all orbits size even (2 or 4). So total counts all even. R odd, C even: similarly all orbits even? Let's check R=3, C=2: rows odd, columns even. Orbits: (1,1): (1,1),(1,2),(3,1),(3,2) size 4. (2,1): (2,1),(2,2) size 2. So all even. So if either R or C is even, all orbits have even size, so total count of each character must be even. If both odd, there is a unique center cell (size 1) so exactly one character can have odd total count (the one assigned to center). That's reminiscent of condition for a single string to be a palindrome.
Now, consider the given row multisets. The total count of each character is just the sum over rows of their counts. So a necessary condition for existence of such a palindrome matrix is: If R*C is the total number of cells, then for each character, its total count must be even except possibly one character if both dimensions are odd. But is this also sufficient given we can rearrange rows? Not exactly, because we also need to be able to assign characters to orbits such that each row's multiset matches. However, maybe with the ability to permute within rows, the necessary parity condition on totals plus the condition that each row individually can be palindrome (i.e., row mask has at most one odd) might be sufficient? Let's test small examples.
Consider R=2, C=2. Both even, so all totals must be even. Row condition: each row's segment must have both characters even counts? Actually for a row of length 2 to be rearranged into a palindrome, the two characters must be equal (since palindrome of length 2 must be two same chars). So each row must consist of two identical characters. So each row's multiset: e.g., row1: 'a','a'; row2: 'b','b'. Then total counts: a:2 (even), b:2 (even). Is it possible to assign a palindrome matrix? We need all four cells same because of earlier reasoning? Actually for 2x2 palindrome matrix, we need all cells equal. Check: row palindrome: row1: X X, row2: Y Y; column palindrome: col1: X Y, col2: X Y. For column palindrome we need X = Y, because col1: X = Y? Wait column palindrome: column 1 must be palindrome of length 2, so X = Y. So indeed X must equal Y. So all cells equal. Therefore with row1 having two a's and row2 having two b's (a≠b), it's impossible. So condition of totals even is not sufficient. So we need more.
Let's analyze: For 2x2, each row must have both characters equal (since row palindrome condition). So each row's multiset is of form {c,c}. Then column palindrome forces that the two rows must have the same character, because column must have two equal characters. So the rows must have identical character. Therefore the row multisets must be identical (same character). So additional condition: The rows must be "compatible" pairwise.
Generalizing: The constraints from symmetries impose that for rows that are symmetric about the vertical center (i.e., rows i and R+1-i), they must have some relation.
Consider the assignment approach: The fundamental block defines values for positions (i0, j0) with i0=1..ceil(R/2), j0=1..ceil(C/2). For each such orbit, the characters assigned must be the same across the four (or two) positions. Then each row i gets contributions from orbits: For rows i that are not the middle row (if any), they are paired: row i and row R+1-i. For each orbit with j0 not on the middle column, that orbit contributes two cells to row i (if i = i0) and two cells to row R+1-i? Actually careful: Let's enumerate orbits.
Define:
- For i0 from 1 to floor(R/2) (lower half) and j0 from 1 to floor(C/2): orbit includes 4 positions: (i0,j0), (i0, C+1-j0), (R+1-i0, j0), (R+1-i0, C+1-j0). Then row i0 gets two cells: (i0,j0) and (i0, C+1-j0). Row R+1-i0 gets two cells: (R+1-i0, j0) and (R+1-i0, C+1-j0). Also note that if C is odd, there is middle column j_mid = (C+1)/2. For i0 in 1..floor(R/2), j0 = j_mid (if included in representatives). But j_mid is its own mirror, so orbits with j0 = j_mid: they have two positions: (i0, j_mid) and (R+1-i0, j_mid). So row i0 gets one cell (since only (i0,j_mid)), row R+1-i0 gets one cell. Similarly if R odd, there is middle row i_mid. For j0 in 1..floor(C/2), orbit includes (i_mid, j0) and (i_mid, C+1-j0) (two cells in the same row? Actually middle row is fixed under row flip. For j0 not middle column, orbit: (i_mid, j0) and (i_mid, C+1-j0) are two distinct positions in the same row, and because there is no other row, so orbit size 2. So row i_mid gets two cells from such orbit. If both i_mid and j_mid, the center cell is alone.
Thus rows come in pairs except possibly the middle row if R odd.
Now, for each pair of rows (i and R+1-i) (with i < R+1-i), the orbits that involve both rows are those with j0 in 1..ceil(C/2) (but specifically those that have two rows). Actually all orbits that have both rows are those where i0 = i (or i0 = R+1-i? The representative is chosen as min(i, R+1-i) so i0 = i). For each such i0, the orbits with j0 from 1..ceil(C/2) contribute some cells to row i0 and row R+1-i0. Let's categorize by j0:
- If j0 <= floor(C/2) (i.e., j0 not middle column when C odd), the orbit has 4 positions: row i0 gets 2 cells (j0 and C+1-j0), row R+1-i0 gets 2 cells.
- If C odd and j0 = (C+1)/2 (middle column), the orbit has 2 positions: row i0 gets 1 cell, row R+1-i0 gets 1 cell.
Thus, for the pair of rows (i, i'), the total number of cells contributed to each row from these shared orbits is: each such orbit contributes the same number of cells to each row? In first case, each gets 2; in second, each gets 1. So the total count of cells in row i and row i' are equal? Not necessarily, because row i may also have contributions from orbits where i is the middle row? But middle row only appears if R odd and i = i_mid. So for a paired rows, both rows have exactly the same number of cells from these orbits. Indeed, from the pairing construction, for any i0 (i0 <= floor(R/2)), the two rows i0 and R+1-i0 have symmetric structure and the total number of cells in each is the same (since the matrix is symmetric). Actually total cells in row i0 equals total cells in row R+1-i0 always because the matrix is just a rectangle: both rows have C cells. But in terms of assignments from orbits, they receive cells from exactly the same number of orbits: each orbit either contributes equally to both rows (in the paired case) or contributes to only one row if it's the middle row case (but that's not a pair). So for a pair, the rows have the same length C, so obviously they have equal number of cells.
Now, what constraints does the column palindrome condition impose between the two rows? Since each column j must be palindrome, the characters in row i0 and row R+1-i0 at column j must be equal. But note also row palindrome condition forces a_{i0, j} = a_{i0, C+1-j}. So the whole assignment must satisfy that for each orbit, all cells have same character. So essentially, for paired rows i and i', they must have exactly the same multiset of characters? Let's check.
Take an orbit of type with 4 cells: characters at (i, j) and (i, C+1-j) are same as (i', j) and (i', C+1-j). So row i gets two cells with the same character (if j0 not middle column). Row i' gets two cells also with that same character. So in that orbit, row i receives two copies of character X, row i' receives two copies of X. For orbit with middle column (j0 middle), each row gets one copy of X. So for each orbit, the two rows get the same number of copies of the assigned character (either 1 or 2). Therefore, if we sum over all orbits that involve both rows (i.e., all j0), the multiset of characters received by row i and row i' are exactly the same, because they are just copies from the same assignments. But careful: Are there orbits that involve only one of the rows? In paired rows, all orbits that include row i also include row i' because they are symmetric. The only exception would be if there is a middle row, but that's not part of a pair. For rows i and i' with i < i', all orbits with representative i0 = i include both rows. For j0 ranging over all columns, we cover all cells in both rows. So indeed, the entire rows are covered by these shared orbits. Therefore, for any paired rows, after assignment, the multiset of characters in row i must be identical to the multiset in row i'.
But wait: Could there be a scenario where we assign different characters to the same orbit? No, orbit forces same character. So indeed, row i and row i' must end up having exactly the same multiset of characters. Since we have the flexibility to assign characters to orbits, we can choose to make them identical as long as the given row segments (original multisets) can be permuted to match this requirement. However, note that we can reorder within each row arbitrarily, but we cannot change the multiset of characters in each row; that's given by the original submatrix. So for a submatrix to be beautiful, it is necessary that for each pair of symmetric rows (i and R+1-i), the multisets of characters (the row segments) are identical. Also, for the middle row (if R odd), there is no partner; its multiset can be arbitrary but must satisfy that we can assign the orbits such that the row gets the required multiset. For the middle row, it receives contributions from orbits where i0 = i_mid (if i_mid is the representative) and j0 from 1..ceil(C/2). For each such j0, the orbit gives either 2 cells (if j0 not middle column) or 1 cell (if j0 middle column) to the middle row. The assignment to these orbits can be chosen to match the middle row's multiset. So no additional pairing constraints for middle row besides the row's own palindrome condition? Actually the row itself must be palindrome; but that condition is already enforced by the orbit structure: if we assign characters to orbits consistently, the row will automatically be palindrome because row palindrome is built into the symmetry (since a_{i,j} = a_{i, C+1-j} due to the orbit). So if we assign characters to orbits arbitrarily, row i will be palindrome by construction. So the row palindrome condition is automatically satisfied if we use the orbit assignment approach. However we also must respect the given row multiset. So for each row, the multiset of characters from its cells (determined by the assignment) must equal the given multiset. That's the constraint.
Thus, the problem reduces to: Given R x C submatrix, with given character counts per row (from original), can we assign characters to orbits (representatives) such that for each row, the multiset of characters (with multiplicities as per the orbits that row participates in) matches the given row multiset? Moreover, because the assignment must be consistent across rows: if an orbit involves two rows, the same character assignment contributes to both rows' multisets. So the row multisets must be consistent across paired rows: they must be exactly equal (since they get identical contributions from each shared orbit). And for the middle row, its multiset must be exactly the multiset formed by the assignments to the orbits that involve it.
So the necessary and sufficient condition is:
- For each pair of rows i and R+1-i (i < R+1-i), the row multisets (i.e., the frequency vectors of characters in the selected columns) must be identical.
- For the middle row (if R odd), there is no additional pairing constraint, but the row's multiset must be such that it can be expressed as a sum of contributions from the orbits that involve it, where each orbit contributes either 1 or 2 copies of a character, and the orbits are independent (we can assign any characters). However, does that impose any restriction beyond the row's own palindrome condition? Let's think: The middle row's cells are partitioned into orbits. Each orbit corresponds to a column pair (if C even) or a single column (if C odd and middle). For the middle row, if C is even, then there are C/2 orbits each of size 2: each orbit gives two cells (j and C+1-j) in the same row, and they must be assigned the same character (since they are in the same orbit? Actually careful: For the middle row (i_mid) when R odd, the orbits that include it are:
- For j0 from 1 to floor(C/2): orbit includes (i_mid, j0) and (i_mid, C+1-j0) only (since row flip gives itself). So orbit size 2, both cells in the same row, and they must be equal (due to orbit equality). So each such orbit contributes two copies of the same character to the middle row.
- If C odd, also the center cell (i_mid, j_mid) is an orbit of size 1, contributes one copy.
Thus, the middle row's multiset must be such that the counts of characters can be partitioned into groups: for each j0 <= floor(C/2), we need two identical characters (i.e., a pair of same character), and possibly one extra single character if C odd. So this is exactly the condition that the row can be rearranged into a palindrome: because for a row of length C, to be a palindrome, we need to be able to pair up characters (each pair of symmetric positions must be equal). That's equivalent to the row's multiset having at most one odd count. Indeed, for a row to be palindrome, we need that for each symmetric pair (j, C+1-j) the characters are equal, so the row can be divided into floor(C/2) pairs of equal characters and possibly a middle character if C odd. This is precisely the condition: the multiset must be such that at most one character has odd count (if C odd) and all others even (if C even then all even). So the middle row must satisfy its own row palindrome condition, which is exactly the condition that its character counts have the appropriate parity. But note: The row palindrome condition is necessary anyway for any row in the submatrix because we need to reorder each row to be palindrome. So this condition is already required for all rows, including the middle one. So does the middle row impose any extra constraint beyond the row palindrome condition? It seems not: given any row multiset that satisfies the palindrome condition (i.e., at most one odd count if length odd, all even if length even), we can always assign characters to the orbits: For each pair of symmetric columns, assign a character that appears an even number of times? Actually to form a palindrome, we need to pair up characters. If the multiset satisfies the parity condition, we can always arrange it as a palindrome. This is standard: we can take characters in pairs to fill symmetric positions. So for the middle row, we can always assign the given multiset to the orbits (each orbit requires two identical chars for the pair positions, and a single char for the center if odd) because we have the flexibility to assign any character to each orbit. So the middle row's condition is exactly the row palindrome condition, and it's automatically feasible given that condition.
What about paired rows? For a pair of rows (i and i'), we need their multisets to be identical. Is that also sufficient? Let's test with the 2x2 example: Row1 multiset = {a,a}, Row2 multiset = {b,b}. They are not identical, so fails. If they were both {a,a}, then condition holds. Can we assign orbits to achieve that? For 2x2, we have a single orbit of size 4 (since R=2 even, C=2 even). So all four cells must have the same character. If both rows have {a,a}, then total multiset is {a,a,a,a} which is consistent with all a's. So we can assign character a to the orbit. Works. So identical multisets for paired rows seem sufficient.
Now consider a more complex case: R=2, C=3. Row1 and Row2 are paired (since R even, no middle row). Both rows must have identical multisets? Let's check: In a 2x3 matrix, with row palindrome and column palindrome, we argued earlier that the two rows must be identical (as strings after reordering). Actually with the orbit structure: For R=2, C=3. Representatives: i0=1 (since floor(R/2)=1). j0 from 1 to floor(C/2)=1? Actually C=3, floor(C/2)=1, and there is middle column j=2. So orbits:
- For j0=1 (j0 <=1, not middle): orbit includes (1,1),(1,3),(2,1),(2,3) size 4. So that's one orbit covering corners.
- For j0=2 (middle column): orbit includes (1,2),(2,2) size 2.
Thus there are two orbits. The assignment: choose a character X for the corner orbit, and Y for the middle orbit. Then row1 gets: from corner orbit two cells (1,1) and (1,3) both X; from middle orbit one cell (1,2) Y. So row1 multiset: two X's and one Y? Wait, row1: positions: (1,1)=X, (1,2)=Y, (1,3)=X => multiset {X, X, Y}. Row2 gets: (2,1)=X, (2,2)=Y, (2,3)=X => same multiset {X, X, Y}. So indeed both rows have identical multisets. So condition: row1 multiset = row2 multiset. Also each row must be able to be palindrome: For length 3, a palindrome pattern is X Y X, which matches exactly the structure (two X's, one Y). That's fine: row palindrome condition is that the row multiset has at most one odd count: Here counts: X:2 even, Y:1 odd. That's okay. So row condition holds automatically if rows are identical? Not necessarily; they could have a multiset that doesn't satisfy row palindrome condition, e.g., {X, Y, Z} three distinct characters, odd counts: three odds? Actually three distinct each count 1 -> three odd counts, not allowed. So both rows must also individually satisfy the row palindrome condition. But if they are identical, does that automatically guarantee each row individually can be palindrome? No, the row's own multiset must satisfy the palindrome condition regardless of pairing. So we also need each row's multiset to satisfy that condition (i.e., at most one odd count if C odd; all even if C even). In 2x3 (C odd), row multisets must have at most one odd count. So condition: For paired rows, they must have identical multisets, and those multisets must satisfy the row palindrome condition.
Now consider the middle row case when R odd. For the middle row, it only needs to satisfy its own row palindrome condition. The paired rows must have identical multisets and also satisfy row palindrome condition? Actually row palindrome condition is required for all rows (since each row individually must be rearrangeable into palindrome). So yes, every row must satisfy its own row palindrome condition. So overall necessary and sufficient conditions:
-
For each row i in the selected submatrix (rows i1..i2), the segment from columns j1..j2 must have a multiset that can form a palindrome: i.e., the number of characters with odd count is at most 1 if the width C is odd; if C is even, then no character may have odd count (i.e., all counts even). Let's denote this as row i being "good" with respect to the column segment.
-
For any two rows that are symmetric with respect to the vertical center of the row interval (i.e., rows i and i' = i1 + i2 - i), their multisets must be exactly equal (as vectors of counts). Note: This includes the case where i = i' (the middle row when R odd) where the condition is vacuously true (since a row is symmetric to itself, equality trivially holds). So effectively, the sequence of row multisets over the row interval must be palindromic! Because symmetry i <-> i' requires equal multisets. That is, the array of row multisets (for the selected column segment) must itself be a palindrome (when considered as a sequence of vectors). Additionally, each row's multiset must satisfy the palindrome condition (as in 1).
Thus, a submatrix is beautiful iff:
- For each row i in the interval, the segment's character count vector (length 26) has at most one odd count if C odd, else zero odd counts. (Row condition)
- The sequence of these count vectors for rows from i1 to i2 is palindromic. (Vertical palindrome condition)
This is a nice simplification! Let's verify with the examples.
Example 1: n=1, m=3, row "aba". For any submatrix (since only one row), vertical palindrome condition is trivial (single row is palindromic). Row condition: For width C, we need that the segment (j1..j2) has at most 1 odd count if C odd, else zero if even. For single character submatrices (C=1): each character's count: 'a' has 1 odd -> okay because 1 odd (max 1). So each single cell is beautiful. For C=2: segments like "ab": counts a=1,b=1 -> two odds, not allowed (since C even requires zero odds). So "ab" not beautiful. For C=3: "aba": counts a=2,b=1 -> one odd (b) -> allowed because C odd. So the only beautiful submatrices are the three single cells and the whole row. That's 4, matches output.
Example 2: n=2, m=3, rows: "aca", "aac". Let's list all beautiful submatrices according to condition. We need both rows satisfy row condition and their count vectors equal (since R=2, the two rows must have identical multisets) for any column interval. Let's test some: Submatrix of size 1x1: each cell individually: row condition holds (single char), vertical condition: single row trivially palindrome? Actually for R=1, vertical palindrome trivially holds (since single row). So all 6 single cells are beautiful? But output total is 11, which includes all submatrixes. Let's count: total submatrices = 23=6? Actually number of submatrices for n=2,m=3 is (23)(34)/2? No, total submatrices = n*(n+1)/2 * m*(m+1)/2 = 23/2? Let's compute: number of row intervals = n(n+1)/2 = 23/2=3. Column intervals = 34/2=6. Total submatrices = 3*6=18. The output is 11, so not all. So single cells are 6, so there are 5 others.
Check row condition for each row individually for each column interval. For a 1-row submatrix, it's just a row segment. So we need row segment to be palindrome-allowed. For row1 "aca": let's compute palindrome condition for each substring:
- Length 1: all ok.
- Length 2: "ac": a=1,c=1 -> two odds -> not allowed (since even length requires zero odds). "ca": c=1,a=1 -> not allowed. "?? Actually row1 substrings: (1,1)-(1,2): "ac" not allowed. (1,2)-(1,3): "ca" not allowed. (1,1)-(1,3): "aca": a=2,c=1 -> one odd allowed.
Row2 "aac": substrings:
- length1: all ok.
- length2: "aa": a=2 -> zero odds allowed. "ac": a=1,c=1 -> two odds not allowed.
- length3: "aac": a=2,c=1 -> one odd allowed.
So for single-row submatrices (R=1), the allowed ones are those row segments that satisfy condition. So from row1: 3 singles + the whole row = 4? Actually row1 singles: 3; length2: none; length3:1 => total 4 for row1 alone. Row2: singles:3; length2: "aa" allowed? Yes; length2 "ac" not; length3:1 => total 3+1+1? Wait count properly: For row2, substrings: positions: (1,1)-(1,1): a, ok; (1,2)-(1,2): a, ok; (1,3)-(1,3): c, ok; (1,1)-(1,2): aa, ok; (1,2)-(1,3): ac, not ok; (1,1)-(1,3): aac, ok. So that's 3+1+1=5? Actually 3 singles + 1 length2 + 1 length3 =5. So total for R=1 submatrices would be 4+5=9? But careful: submatrices with R=1: there are 3 row intervals? Actually row intervals of length1: two possibilities: row1 alone and row2 alone. So total submatrices with R=1: for each row, number of column intervals that are beautiful for that row. Row1: 4, Row2:5 => total 9. Output is 11, so remaining 2 submatrices have R=2 (both rows). So there are 2 beautiful submatrices that include both rows.
Now check R=2 submatrices: They require both rows satisfy row condition for the column interval, and their count vectors must be identical. Let's enumerate column intervals (width C):
- C=1: segments of length1. For each column j, check row1 and row2 characters. Need both rows palindrome condition: for C=1, it's always ok (odd length, any single char allowed). And need count vectors equal, i.e., row1's char must equal row2's char. So columns where both rows have same char: column1: row1='a', row2='a' -> same => beautiful. column2: row1='c', row2='a' -> not same. column3: row1='a', row2='c' -> not same. So only column1 qualifies. That's one.
- C=2: consider intervals of two columns: (1,2): rows segments: row1="ac", row2="aa". Row1: counts a=1,c=1 -> two odds, not allowed (since C even requires zero odds). So fails row condition for row1.
(2,3): row1="ca", row2="ac". Row1: c=1,a=1 -> two odds not allowed. So fails.
- C=3: whole width: row1="aca", row2="aac". Row1: a=2,c=1 -> allowed (C odd, one odd). Row2: a=2,c=1 -> allowed. Also count vectors: both have a=2,c=1 -> identical. So qualifies. That's the second beautiful submatrix with R=2.
Thus total beautiful submatrices = 9 + 2 = 11. This matches output.
So our condition seems correct.
Now verify with example 3 given? We'll trust.
Thus the problem reduces to: count all submatrices (contiguous row interval, contiguous column interval) such that:
- For each row i in the interval, the substring from l to r (columns) has a character count vector that satisfies: number of characters with odd count ≤ 1 if (r-l+1) odd, else =0.
- The sequence of these count vectors for rows from i1 to i2 is palindromic (i.e., symmetric).
Now we need to count these submatrices efficiently for n,m ≤ 250. Total rows n=250, columns m=250. Naively checking all O(n^2 m^2) submatrices is too large (≈3.9e9). We need something like O(n^2 * m) or O(m^2 * n) or better.
We can fix a range of columns (left, right) and then consider rows. For each fixed column segment [l, r], we compute for each row i a value that represents the count vector of that row segment, and also a flag indicating if it satisfies the row palindrome condition. Then we need to count number of contiguous row intervals where the sequence of these row values is palindromic (i.e., symmetric) and also each row's value is "good" (i.e., satisfies condition). But note: The row palindrome condition is about the substring itself, and it's independent of other rows. So for a given column segment, we can mark rows as "bad" if the substring doesn't satisfy the row condition. Then we need to count palindromic contiguous intervals in the array of row values (vectors) that consist only of good rows? Actually even if a row is bad, the submatrix containing it cannot be beautiful because that row wouldn't satisfy row condition. So we only consider intervals where all rows are good.
Now, the vertical palindrome condition requires that the sequence of row vectors is a palindrome. That is, for the interval of rows [top, bottom], we need that for all k from 0 to length-1, row vector at top+k equals row vector at bottom-k.
Thus, for a fixed column segment, we need to count palindromic subarrays in an array of length n (rows), where each element is a vector (26 counts) or some hash, and we only consider subarrays where all elements are "good". And we need to count all such palindromic subarrays.
But we also have to consider that the column segment itself must have a certain width parity? Actually row condition depends on width parity: if width (r-l+1) is even, each row must have all character counts even; if odd, at most one odd. So the definition of "good" row depends on the parity of width. That's okay.
Now, number of column segments is O(m^2) ≈ 31k (since m=250, m^2=62500). For each column segment, we need to process rows. If we process each segment independently by recomputing row vectors from scratch, that would be O(m^2 * n * 26) which is 62500 * 250 * 26 ≈ 406 million, maybe borderline but possibly okay in C++ with optimizations? 400 million operations could be okay (2-3 seconds?) but we also need to count palindromic subarrays efficiently. Counting all palindromic subarrays in an array of length n can be O(n^2) if done naively (checking each interval). That would be too large: for each of 62.5k column segments, O(n^2) would be 62.5k * 62.5k? Actually n=250, n^2 = 62500, so total O(m^2 * n^2) = (62500 * 62500) = 3.9e9 again. Too high.
We need to count palindromic intervals more efficiently. Since n is only 250, maybe O(n^2) per column segment is acceptable? Let's compute: m^2 = 62500, n^2 = 62500, product = 3.9e9, too high.
We need to do better.
We could fix top and bottom rows and then expand columns? Or maybe we can treat both dimensions symmetrically. Since both n and m are up to 250, we might try O(n^2 * m) or O(m^2 * n). For each pair of rows (top, bottom), we consider the column segments where the rows between top and bottom form a palindrome (vertical palindrome) and each row's segment is good. Then we need to count column intervals that satisfy that for all rows in [top,bottom], the row vectors are equal when mirrored? Wait vertical palindrome condition involves all rows in the interval, not just top and bottom. For a fixed row interval [top, bottom], the condition is that for all i from top to bottom, the row vector of row i must equal the row vector of row (top+bottom-i). So that's a condition on the entire interval.
If we fix top and bottom, we could perhaps iterate over columns and maintain some data structure. But there are O(n^2) row intervals (≈31250) and m=250, so O(n^2 * m) = ~7.8 million, which is fine. Then we can maybe for each row interval, count number of column intervals where the submatrix is beautiful. But we need to account that the row interval must be such that the rows are symmetric in terms of their row vectors for the column segment. This is like: For a fixed row interval [top, bottom], we need to count column intervals [l,r] such that:
- For each row i in [top, bottom], the substring from l to r is "good" (i.e., satisfies row condition for width C = r-l+1).
- And the sequence of row vectors (for that column interval) is palindromic vertically, i.e., for each i, vector(row i) equals vector(row sym(i)).
But note that the vectors depend on the column interval. So for each row i, we have an array across columns of its cumulative counts. To check a column interval, we need to compute the count vector for that interval for each row.
If we fix row interval, we can precompute for each row i a 26-bit parity mask for each prefix (or for each possible l,r). But we need to check condition across rows quickly.
Observation: The vertical palindrome condition essentially says that for each pair of symmetric rows (i and sym(i)), their count vectors over the column interval must be equal. So for the row interval to be valid for a given column interval, we need that for all i from top to bottom, the vector of row i equals the vector of row sym(i). Since sym(i) = top+bottom - i. So we can define for each row i its "difference" relative to its symmetric counterpart. But careful: The condition must hold for the entire interval simultaneously.
If we fix the row interval, we can define for each column position something like a fingerprint that aggregates the condition across rows. For each column l,r, we can compute the parity masks for each row? Another idea: Since n is small, we could for each pair of columns (l,r) compute the row vectors and then find palindromic row intervals