[UVA] 10074 - Take the Land
Problem E
Take the Land
Input : standard input
Output : standard output
The poor man went to the King and said, “Lord, I cannot maintain my family. Please give me some wealth so that I can survive with my wife and children.” The King replied, “I shall grant you a piece of land so that you can cultivate and grow food for your family. In the southern part of the Kingdom there is a rectangular forest. Trees have been planted there at regular intervals. Some of the trees have been cut for use. You are allowed to take any rectangular piece of land that does not contain any tree. You need not go to the forest to select the piece of land. I have a map containing 1s at places where there is a tree and 0s at points where the tree has been cut.”
Help the poor man to find out the largest piece of land. Area of the land is measured in units of number of trees that were there. Your program should take a matrix of 1s and 0s as input and output the area of the largest rectangular piece of land that contain no tree. Be careful about the efficiency of your program.
Input
The input file may contain multiple test cases. The first line of each test case contains two integers M and N (1<=M,N<=100) giving the number of rows and columns in the matrix that follows. Each of the next M lines contains N symbols (either 0 or 1). Two consecutive symbols in a line will be separated by a single space. The input terminates with two zeros for M and N.
Output
For each test case in the input print a line giving the area (in terms of the number of trees were there) of the largest rectangular piece of land containing no tree.
Sample Input
6 70 1 1 0 1 1 0
0 0 0 0 0 1 0
1 0 0 0 0 0 1
0 1 0 0 0 0 1
1 1 0 0 0 1 0
1 1 0 1 1 0 0
0 0
Sample Output
12做法 : DP
時間複雜度 O(N^2*M)
#include <stdio.h>
int main() {
int m, n;
while(scanf("%d %d", &n, &m) == 2) {
if(n == 0 && m == 0)
break;
int i, j, k, map[100][100];
for(i = 0; i < n; i++)
for(j = 0; j < m; j++)
scanf("%d", &map[i][j]);
int max = 0, tmp, length, width;
for(i = 0; i < n; i++) {
int sum[100] = {};
for(j = i; j < n; j++) {
for(k = 0; k < m; k++) {
sum[k] += !map[j][k];
if(k == 0 || tmp != length*width)
tmp = 0, length = 0;
length++, width = j-i+1;
tmp += sum[k];
if(tmp == length*width)
max = max > tmp ? max : tmp;
}
}
}
printf("%d\n", max);
}
return 0;
}