题意:在01矩阵中求极大全1矩阵数量
极大全1矩阵满足以下两个条件:
1.矩阵内元素全部由1构成
2.该矩阵不是其他全1矩阵的子矩阵
题解:枚举每一行,以该行作为矩阵的底,利用单调栈处理出该行上最大全1矩阵,并判断该矩阵有没有可能向下扩展
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef pair<int, int> pii; const int maxn = 3e3 + 5; char mp[maxn][maxn]; int h[maxn][maxn]; int main() { int n, m; scanf("%d%d", &n, &m); for (int i = 1; i <= n; ++i) { scanf("%s", mp[i] + 1); } for (int i = 1; i <= n; ++i) for (int j = 1; j <= m; ++j) if (mp[i][j] == '1') { h[i][j] = h[i - 1][j] + 1; } int ans = 0; for (int i = 1; i <= n; ++i) { stack<pii> sta; int flag = -1; for (int j = 1; j <= m + 1; ++j) { int pos = j; while (!sta.empty() && sta.top().first > h[i][j]) { if (sta.top().second <= flag) ans++; pos = sta.top().second; sta.pop(); } if (!h[i + 1][j]) flag = j; //判断下面一层是否全1 if (h[i][j] && (sta.empty() || (sta.top().first < h[i][j]))) sta.push(pii(h[i][j], pos)); } } printf("%d ", ans); return 0; }