题解:
先求出每列与每行的前缀和,然后逐行计算答案。
具体的,枚举每行每个点,单调栈求出以该点往上的高度往左往右能够扩展的左右边界 L 和 R。然后判断该点下一行的 L 到 R 之间是不是都被 1 占满,如果不是,则答案加一。
由于每个矩形底边的元素都会重复计算一次,则用哈希去重即可。
代码:
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
#define int ll
#define PI acos(-1.0)
#define INF 0x3f3f3f3f3f3f3f3f
#define P pair<int, int>
#define fastio ios::sync_with_stdio(false), cin.tie(0)
const int mod = 998244353;
const int M = 1000000 + 10;
const int N = 3000 + 10;
int n, m;
int a[N][N];
stack<int> st;
unordered_map<int, int> mp;
int pre[N][N], ans;
signed main()
{
fastio;
cin >> n >> m;
for(int i = 1; i <= n; i ++) {
string s; cin >> s; s = '0' + s;
for(int j = 1; j <= m; j ++) {
if(s[j] == '1') {
a[i][j] = a[i - 1][j] + 1;
pre[i][j] = 1;
}
pre[i][j] += pre[i][j - 1];
}
}
for(int i = 1; i <= n; i ++) {
while(st.size()) st.pop();
int l[N], r[N];
a[i][0] = a[i][m + 1] = -INF;
for(int j = 1; j <= m + 1; j ++) {
while(st.size() && a[i][j] < a[i][st.top()]) r[st.top()] = j - 1, st.pop();
st.push(j);
}
while(st.size()) st.pop();
for(int j = m; j >= 0; j --) {
while(st.size() && a[i][j] < a[i][st.top()]) l[st.top()] = j + 1, st.pop();
st.push(j);
}
mp.clear();
for(int j = 1; j <= m; j ++) {
if(a[i][j] && (r[j] - l[j] + 1) != pre[i+1][r[j]] - pre[i+1][l[j]-1] && mp[l[j]] != r[j]) {
ans ++;
mp[l[j]] = r[j];
}
}
}
cout << ans << endl;
return 0;
}
/*
Rejoicing in hope, patient in tribulation.
*/