Table of Contents

ExplanationImplementation

Official Analysis (in Romanian)

Explanation

Let's start from a more simple case, when the grid will only contain letters a and b. Let's associate for each letter a value corresponding to its position in the alphabet (for now, a equals 00 and b equals 11). Now we will have to find the number of submatrices such that we have ones in the top left and bottom right corners we have 11 and we have 00 everywhere else.

Let's construct another grid of size n×nn \times n where b(i,j)b(i, j) stores the number of consecutive 00 on the column jj above the position (i,j)(i, j).

Now for each line from 22 to nn, for a given position (i,j)(i, j) which is equal to 11 (we will consider this the bottom-right corner), we will move from right to left on that line to find the values equal to 11 placed at coordinates (i,k)(i, k) where k<jk < j such that b(i,k)>0b(i, k) > 0 and b(i,k)b(i, k) strictly smaller than all values b(i,p)b(i, p) with pp between k+1k+1 and jj.

The complexity of this approach is O(n2)\mathcal{O}(n^2).

Now we need to generalize for the entire grid, which has all lowercase letters of the alphabet. At each step, we fix a letter, let's call it chch.

For that letter, we will now create a grid where the positions corresponding to all the letters which are smaller than chch will be equal to 00, all letters equal to chch will be equal to 11 and all letters greater than chch will be equal to 22.

Just like we did it for the binary grid, we will count how many submatrices have values equal to 00 except for the two corners aforementioned. In order to avoid overcounting, we will only count the submatrices such that they contain 11 in at least a corner. Now, when we process a position (i,j)(i, j) we will do as such: if on that position we have 11, we will count the number of previous position which correspond to both 11 and 22, and if on the same position we have 22, we will only count the previous positions that are equal to 11.

The complexity of this approach is still O(n2)\mathcal{O}(n^2) for each letter, which gives us an overall complexity of O(sigma×n2)\mathcal{O}(sigma \times n^2), where sigma=26sigma = 26 is the length of the alphabet.

For other approaches, you can also check out the user solutions on Infoarena, just make sure to press that popup you receive after you first click on a solution.

Implementation

Time Complexity: O(26N2)\mathcal{O}(26 \cdot N^2)

C++

#include <bits/stdc++.h>
using namespace std;
int main() {
ifstream f("ssdj.in");
int n;
f >> n;
long long ans = 0;

Join the USACO Forum!

Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!