您的位置:首页 > 其它

【九度OJ合集】P1465-P1515

2014-09-04 16:43 169 查看
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]
;
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
;
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]
;
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
;
int[] left=new int
;
int[] right=new int
;
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);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: