简要题意:给定一个大小为 的 01 矩阵,求其中有多少个面积 的全 0 子矩阵。
前置知识:P1950 长方形。
在求解上面的问题时,对于第 行的第 个位置,设其上方的 0 的高度为 。使用单调栈求出该位置左侧第一个高度 严格小于 的位置,记为 ;求出该位置右侧第一个高度 小于等于 的位置,记为 。
如果不考虑面积 的限制,显然这样的矩形个数有 个。
在加上面积 的限制之后,我们可以得到如下做法:
-
设 。不妨 ,反之同理。
-
刻画 不考虑面积 ,并固定高度 时,矩形的 宽为 的方案数,有如下的分段函数:
-
不难发现上式是一个可以二阶差分的式子。于是我们可以反推出矩形宽度为 时的方案数。
-
加入高度条件,容易发现高度更大的必然满足高度较小的要求,即对于 ,令 。这样就求出了在高度为 时,宽度为 的矩形个数。
-
最后统计答案时,如果 ,那么将这种情况计入答案。
时间复杂度 。
#include <iostream>
#include <vector>
#include <stack>
using namespace std;
const int maxn = 5e5 + 10;
int n, m, k, h[maxn], r[maxn];
vector<int> a[maxn];
vector<long long> dp[maxn];
stack<int> stk;
long long ans = 0;
int main() {
scanf("%d%d%d", &n, &m, &k);
for (int i = 1; i <= n; i++) {
a[i].resize(m + 2);
dp[i].resize(m + 3);
for (int j = 1; j <= m; j++) {
char c = getchar();
while (c != '#' && c != '.') c = getchar();
if (c == '#') a[i][j] = 1;
else a[i][j] = 0;
}
}
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
if (j <= m) {
if (a[i][j] == 0) h[j]++;
else h[j] = 0;
}
}
for (int j = m; j >= 1; j--) {
while (!stk.empty() && h[stk.top()] > h[j]) stk.pop();
r[j] = stk.empty() ? m + 1 : stk.top(); stk.push(j);
}
while (stk.size()) stk.pop();
for (int j = 1; j <= m; j++) {
while (!stk.empty() && h[stk.top()] >= h[j]) stk.pop();
int l = stk.empty() ? 0 : stk.top();
// [l] ... j ... [r],不妨 r-j >= j-l
// 1:+1 2:+2 ... j-l+1:+(j-l+1) j-l+2:+(j-l+1) ...
// r-j+1:+(j-l+1) r-j+2:+(j-l) ... r-l+1:+1 r-l+2:0 r-l+3:0
// 差分后: 011...110 0...00-1-1...-1-100
// 再次差分后:010...00-10...00-1 0... 0 010
if (h[j]) {
int x = j - l, y = r[j] - j; if (x > y) swap(x, y);
dp[h[j]][1]++; dp[h[j]][x + 1]--;
dp[h[j]][y + 1]--; dp[h[j]][x + y + 1]++;
}
stk.push(j);
}
while (stk.size()) stk.pop();
}
for (int i = n; i >= 1; i--) {
for (int j = 1; j <= m; j++) dp[i][j] += dp[i][j - 1];
for (int j = 1; j <= m; j++) dp[i][j] += dp[i][j - 1];
for (int j = 1; j <= m; j++) {
if (i != n) dp[i][j] += dp[i + 1][j];
if (i * j <= k) ans += dp[i][j];
}
}
printf("%lld", ans);
return 0;
}