|
| 1 | +/* |
| 2 | + * Loop through all the characters; we'll find the number of submatrices that has |
| 3 | + * one of the corners as the current character c. |
| 4 | + * |
| 5 | + * For a given character c, define above[i][j] = the first row r above row i such that |
| 6 | + * A[r][j] >= c. |
| 7 | + */ |
| 8 | + |
| 9 | +#include <bits/stdc++.h> |
| 10 | + |
| 11 | +using namespace std; |
| 12 | + |
| 13 | +using ll = long long; |
| 14 | +#define ii pair<int, int> |
| 15 | +#define f first |
| 16 | +#define s second |
| 17 | +#define pb push_back |
| 18 | +#define mp make_pair |
| 19 | +#define all(x) x.begin(), x.end() |
| 20 | +#define sz(x) (int)x.size() |
| 21 | +#define F0R(i, n) for (int i = 0; i < n; i++) |
| 22 | +#define FOR(i, a, b) for (int i = a; i < b; i++) |
| 23 | +#define inf 1000000010 |
| 24 | + |
| 25 | +int main() { |
| 26 | + cin.tie(0)->sync_with_stdio(0); |
| 27 | + freopen("ssdj.in", "r", stdin); |
| 28 | + freopen("ssdj.out", "w", stdout); |
| 29 | + |
| 30 | + int n; cin >> n; |
| 31 | + char A[n][n]; |
| 32 | + F0R(i, n) F0R(j, n) cin >> A[i][j]; |
| 33 | + |
| 34 | + int above[n][n]; // index of row above (i, j) that's >= c |
| 35 | + int ans = 0; |
| 36 | + for (char c = 'z'; c >= 'a'; c--) { |
| 37 | + F0R(col, n) { |
| 38 | + int prev = -1; |
| 39 | + F0R(row, n) { |
| 40 | + above[row][col] = prev; |
| 41 | + if (A[row][col] >= c) { |
| 42 | + prev = row; |
| 43 | + } |
| 44 | + } |
| 45 | + } |
| 46 | + F0R(row, n) { |
| 47 | + int rightCol = -1; |
| 48 | + int upperBound = -2; |
| 49 | + for (int col = n-1; ~col; col--) { |
| 50 | + if (A[row][col] >= c) { |
| 51 | + rightCol = col; |
| 52 | + upperBound = above[row][col]+1; |
| 53 | + } else { |
| 54 | + if (rightCol == -1) continue; |
| 55 | + if (upperBound <= above[row][col]) { |
| 56 | + if (A[row][rightCol] == c || A[above[row][col]][col] == c) { |
| 57 | + ans++; |
| 58 | + } |
| 59 | + upperBound = above[row][col]+1; |
| 60 | + } |
| 61 | + } |
| 62 | + } |
| 63 | + } |
| 64 | + } |
| 65 | + cout << ans << endl; |
| 66 | + |
| 67 | + return 0; |
| 68 | +} |
0 commit comments