P1497
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StreamTokenizer;
public class Exercise1497
{
public static void main(String[] args) throws IOException
{
StreamTokenizer sc = new StreamTokenizer(new BufferedReader(
new InputStreamReader(System.in)));
while (sc.nextToken() != StreamTokenizer.TT_EOF) {
int m = (int) sc.nval;
sc.nextToken();
int n = (int) sc.nval;
int[][] a = new int[m][n];
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++) {
sc.nextToken();
a[i][j] = (int) sc.nval;
}
int[] h = new int[n];
int left;
int right;
int max = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (a[i][j] == 1)
h[j]++;
else
h[j] = 0;
}
for (int j = 0; j < n; j++) {
if (h[j] == 0)
continue;
left = j;
right = j;
while (left >= 0 && h[left] >= h[j])
left--;
while (right <= n - 1 && h[right] >= h[j])
right++;
int square = h[j] * (right - left - 1);
if (square > max)
max = square;
}
}
System.out.println(max);
}
}
}
找出第i行第j列的高度,并寻找左右的宽度,超时
优化:对于左边,如果h[j-1]<h[j],则找到左边界j
如果h[j-1]>h[j],则可以从h[j-1]对应的列开始继续向左寻找
右边同理(注意从n递减)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StreamTokenizer;
public class Exercise1497
{
public static void main(String[] args) throws IOException
{
StreamTokenizer sc = new StreamTokenizer(new BufferedReader(
new InputStreamReader(System.in)));
while (sc.nextToken() != StreamTokenizer.TT_EOF) {
int m = (int) sc.nval;
sc.nextToken();
int n = (int) sc.nval;
int[][] a = new int[m][n];
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++) {
sc.nextToken();
a[i][j] = (int) sc.nval;
}
int[] h = new int[n];
int[] left=new int[n];
int[] right=new int[n];
int max = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (a[i][j] == 1)
h[j]++;
else
h[j] = 0;
}
for (int j = 0; j < n; j++) {
if (h[j] == 0)
continue;
int k=j;
while (k> 0 && h[k-1] >= h[j])
k=left[k-1];
left[j]=k;
}
for (int j = n-1; j >=0; j--) {
if (h[j] == 0)
continue;
int k=j;
while (k<n-1&&h[k+1]>=h[j])
k=right[k+1];
right[j]=k;
int square = h[j] * (right[j] - left[j] + 1);
if (square > max)
max = square;
}
}
System.out.println(max);
}
}
}