戳我看题
题意:给一个01矩阵,问全是 1 且不被其他全是 1 的矩阵完全包含 的子矩阵的个数。
思路:和求最大全是 1 的子矩阵大小写法类似。想必都知道最大全是 1 的子矩阵大小这个问题是利用单调栈维护每一行为基底的高,其实每一次计算面积的时候,可以确定 左 右 上边界,也就是说 往 左 右 上 都是不可以在扩展的,所以只需要利用前缀和,就能 O(1) 的判断这个位置能否继续向下扩展,不能则 ans ++
Code:
#include<bits/stdc++.h>
#define debug(x) cout << "[" << #x <<": " << (x) <<"]"<< endl
#define pii pair<int,int>
#define clr(a,b) memset((a),b,sizeof(a))
#define rep(i,a,b) for(int i = a;i < b;i ++)
#define pb push_back
#define MP make_pair
#define LL long long
#define ull unsigned LL
#define ls i << 1
#define rs (i << 1) + 1
#define fi first
#define se second
#define CLR(a) while(!(a).empty()) a.pop()
using namespace std;
inline LL read() {
LL s = 0,w = 1;
char ch = getchar();
while(!isdigit(ch)) {
if(ch == '-') w = -1;
ch = getchar();
}
while(isdigit(ch))
s = s * 10 + ch - '0',ch = getchar();
return s * w;
}
inline void write(LL x) {
if(x < 0)
putchar('-'), x = -x;
if(x > 9)
write(x / 10);
putchar(x % 10 + '0');
}
const int maxn = 3100;
int pre[maxn][maxn];
char a[maxn][maxn];
int Hei[maxn][maxn];
int n,m;
stack<int>st;
void solve(){
int ans = 0;
for(int i = 1;i <= n;++ i){
CLR(st);
Hei[i][m + 1] = 0;
for(int j = 1;j <= m + 1;++ j){
if(st.empty() || Hei[i][st.top()] <= Hei[i][j]){
st.push(j);
continue;
}
int top;
while(!st.empty() && Hei[i][st.top()] > Hei[i][j]){
top = st.top(); st.pop();
int rig = j - 1,lef = top;
// printf("====>%d %d %d\n",top,lef,rig);
if(Hei[i][lef - 1] < Hei[i][lef] && pre[i + 1][rig] - pre[i + 1][lef - 1] < rig - lef + 1)
++ ans;
}
Hei[i][top] = Hei[i][j];
st.push(top);
}
}
write(ans); putchar('\n');
}
int main() {
//#ifndef ONLINE_JUDGE
// freopen("in.txt", "r", stdin);
// freopen("out.txt", "w", stdout);
//#endif
n = read(),m = read();
for(int i = 1;i <= n;++ i){
for(int j = 1;j <= m;++ j){
scanf(" %c",&a[i][j]);
Hei[i][j] = (a[i][j] == '1' ? Hei[i - 1][j] + 1 : 0);
pre[i][j] = pre[i][j - 1] + a[i][j] - '0';
}
}
solve();
return 0;
}