#include <bits/stdc++.h>
#include "rect.h"
using namespace std;
#define ll long long
// #define int ll
#define FOR(i, a, b) for (int i = (a); i < (b); i++)
#define REP(i, n) FOR(i, 0, n)
#define RREP(i, n) for (int i = (n)-1; i >= 0; i--)
#define RREP1(i, n) for (int i = (n); i >= 1; i--)
#define REP1(i, n) FOR(i, 1, n+1)
#define pii pair<int, int>
#define ppi pair<pii, int>
#define pip pair<int, pii>
#define f first
#define s second
#define pb push_back
#define ALL(x) (x).begin(), (x).end()
#define SZ(x) (int)((x).size())
#define endl '\n'
#define IOS() ios::sync_with_stdio(false), cin.tie(0), cout.tie(0)
const ll maxn = 2505;
const ll inf = 1e9;
const ll mod = 998244353;
ll pw(ll x, ll p, ll m){
ll ret = 1;
while(p > 0){
if (p & 1){
ret *= x;
ret %= m;
}
x *= x;
x %= m;
p >>= 1;
}
return ret;
}
ll inv(ll x, ll m){
return pw(x, m-2, m);
}
int n, m;
vector<pii> rngr[maxn][maxn], rngd[maxn][maxn]; // given row, then column, the ok ranges
ll count_rectangles(vector<vector<int>> arr){
n = SZ(arr);
m = SZ(arr[0]);
for (int i = 1; i <= n-2; i++){
stack<pii> st;
int lim = m+5;
for (int j = m-1; j >= 0; j--){
// subtask
while(SZ(st)){
if (st.top().s != j+1){
rngr[i][j+1].pb({j+1, st.top().s-1});
}
if (st.top().f > arr[i][j]) break;
if (st.top().f == arr[i][j]) {
st.pop();
break;
}
st.pop();
}
st.push({arr[i][j], j});
}
}
for (int j = 1; j <= m-2; j++){
stack<pii> st;
int lim = n+5;
for (int i = n-1; i >= 0; i--){
// subtask
while(SZ(st)){
if (st.top().s != i+1){
rngd[i+1][j].pb({i+1, st.top().s-1});
}
if (st.top().f > arr[i][j]) break;
if (st.top().f == arr[i][j]) {
st.pop();
break;
}
st.pop();
}
st.push({arr[i][j], i});
}
}
ll ans = 0;
map<pii, pii> mp;
for (int i = n-2; i >= 1; i--){
vector<int> cnt(n);
REP1(j, m-1){
REP(k, n) cnt[k] = 0;
int pre = j;
for (auto qrng:rngr[i][j]){
while(pre <= qrng.s){
for (auto mrng:rngd[i][pre]){
cnt[mrng.s]++;
}
pre++;
}
int upbd = i;
if (mp.count(qrng) && mp[qrng].f == i+1){
upbd = mp[qrng].s;
mp[qrng].f = i;
}
else mp[qrng] = {i, i};
FOR(k, i, upbd+1) ans += (cnt[k] == qrng.s-j+1);
}
}
}
return ans;
}
/*
signed main(){
cout<<count_rectangles({{4, 8, 7, 5, 6},
{7, 4, 10, 3, 5},
{9, 7, 20, 14, 2},
{9, 14, 7, 3, 6},
{5, 7, 5, 2, 7},
{4, 5, 13, 5, 6}})<<endl;
}
*/
/*
4 4
1 2
2 3
3 1
1 4
*/
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |