Largest Submatrix of All 1’s
Time Limit: 5000MS Memory Limit: 131072K
Total Submissions: 7390 Accepted: 2664
Case Time Limit: 2000MS
Description
Given a m-by-n (0,1)-matrix, of all its submatrices of all 1’s which is the largest? By largest we mean that the submatrix has the most elements.
Input
The input contains multiple test cases. Each test case begins with m and n (1 ≤ m, n ≤ 2000) on line. Then come the elements of a (0,1)-matrix in row-major order on m lines each with n numbers. The input ends once EOF is met.
Output
For each test case, output one line containing the number of elements of the largest submatrix of all 1’s. If the given matrix is of all 0’s, output 0.
Sample Input
2 2
0 0
0 0
4 4
0 0 0 0
0 1 1 0
0 1 1 0
0 0 0 0
Sample Output
0
4
题目链接:POJ 3494
由于是最大全$1$矩阵,其实跟直方图的最大矩形是一样的,预处理出每一个点向上连续的最大高度,然后对每一行做一次最大面积直方图算法即可。
代码:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
using namespace std;
typedef pair<int, int> pii;
typedef long long LL;
const double PI = acos(-1.0);
const int N = 2010;
int G[N][N], H[N][N];
int L[N], R[N];
inline int solve(int arr[], int l, int r)
{
int ret = 0;
stack<int>st;
for (int i = l; i <= r; ++i)
{
while (!st.empty() && arr[st.top()] >= arr[i])
st.pop();
L[i] = st.empty() ? l : st.top() + 1;
st.push(i);
}
while (!st.empty())
st.pop();
for (int i = r; i >= l; --i)
{
while (!st.empty() && arr[i] <= arr[st.top()])
st.pop();
R[i] = st.empty() ? r : st.top() - 1;
ret = max(ret, arr[i] * (R[i] - L[i] + 1));
st.push(i);
}
return ret;
}
int main(void)
{
int n, m, i, j;
while (~scanf("%d%d", &n, &m))
{
for (i = 1; i <= n; ++i)
for (j = 1; j <= m; ++j)
scanf("%d", &G[i][j]);
for (i = 1; i <= m; ++i)
{
int sum = 0;
for (j = 1; j <= n; ++j)
{
if (G[i][j])
++sum;
else
sum = 0;
H[j][i] = sum;
}
}
int ans = 0;
for (i = 1; i <= n; ++i)
ans = max(ans, solve(H[i], 1, m));
printf("%d\n", ans);
}
return 0;
}