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 and b equals ). 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 and we have everywhere else.
Let's construct another grid of size where stores the number of consecutive on the column above the position .
Now for each line from to , for a given position which is equal to (we will consider this the bottom-right corner), we will move from right to left on that line to find the values equal to placed at coordinates where such that and strictly smaller than all values with between and .
The complexity of this approach is .
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 .
For that letter, we will now create a grid where the positions corresponding to all the letters which are smaller than will be equal to , all letters equal to will be equal to and all letters greater than will be equal to .
Just like we did it for the binary grid, we will count how many submatrices have values equal to except for the two corners aforementioned. In order to avoid overcounting, we will only count the submatrices such that they contain in at least a corner. Now, when we process a position we will do as such: if on that position we have , we will count the number of previous position which correspond to both and , and if on the same position we have , we will only count the previous positions that are equal to .
The complexity of this approach is still for each letter, which gives us an overall complexity of , where 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:
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!