Hi!!!!
I have no idea why i get WA!!
the algorithm I use goes like this:
every two points (r1, c1) and (r2, c2) define exactly one rectangle if and only if
r1 != r2 and c1 != c2 (its easy to figure this out)
In my program r1 < r2 and c1 < c2
now the scanning goes like this: I check all the possible rectangles.
This is by done by defining one point as constant and by changing the coordinates
of the other point and vice versa.
Checking whether the rectangle created by (r1, c1) and (r2, c2) is a valid one (i.e has no trees) takes O(c2 - c1) because answering to the question how many trees
are between (r2, c) and (r2, c) takes O(1) for c1 <= c <= c2 (see countTrees for that)
That my code:
Code: Select all
#include <stdio.h>
#define MAXSIZE 100
#define white 0
#define black !white
int a[MAXSIZE + 1][MAXSIZE];
int m, n;
void init()
{
int i;
for(i = 0; i < n; i++) {
a[0][i] = white;
}
}
void countTrees()
{
int i, j;
for(i = 1; i <= m; i++) {
for(j = 0; j < n; j++) {
a[i][j] += a[i - 1][j];
}
}
}
int treesNum(int r1, int r2, int c)
{
return (a[r2][c] - a[r1 - 1][c]);
}
int isValidRect(int r1, int c1, int r2, int c2)
{
for(; c2 >= c1; c2--) {
if (treesNum(r1, r2, c2) > 0) {
return 0; /* not a VALID rectangle */
}
}
return 1; /* a VALID rectangle */
}
/* r2 and c2 remain constant here */
int calcRect(int r2, int c2)
{
int r1, c1;
for(r1 = 1; r1 < r2; r1++) {
for(c1 = 0; c1 < c2; c1++) {
if (isValidRect(r1, c1, r2, c2)) { /* i.e no trees */
return (r2 - r1 + 1) * (c2 - c1 + 1);
}
}
}
return 0;
}
int solve()
{
int maxRect = 0;
int temp;
int r2, c2;
for(r2 = m; r2 > 1; r2--) {
for(c2 = n - 1; c2 > 0; c2--) {
/* if the maximum potential rectangle is smaller then
the maximum rectangle we currently have we finish */
if (maxRect > (r2 * n)) {
return maxRect;
}
temp = calcRect(r2, c2);
if (maxRect < temp) {
maxRect = temp;
}
}
}
return maxRect;
}
int main()
{
int i, j;
while (scanf("%d%d", &m, &n) == 2) {
if ( (m == 0) && (n == 0) ) break;
init();
for(i = 1; i <= m; i++) {
for(j = 0; j < n; j++) {
scanf("%d", &a[i][j]);
}
}
countTrees();
printf("%d\n", solve());
}
return 0;
}
Please try to help me here guys thanx!!