USACO Section 3.3 Home on the Range(dp)

Home on the Range

Farmer John grazes his cows on a large, square field N (2 <= N <= 250) miles on a side (because, for some reason, his cows will only graze on precisely square land segments). Regrettably, the cows have ravaged some of the land (always in 1 mile square increments). FJ needs to map the remaining squares (at least 2x2 on a side) on which his cows can graze (in these larger squares, no 1x1 mile segments are ravaged).

Your task is to count up all the various square grazing areas within the supplied dataset and report the number of square grazing areas (of sizes >= 2x2) remaining. Of course, grazing areas may overlap for purposes of this report.

PROGRAM NAME: range

INPUT FORMAT

Line 1: N, the number of miles on each side of the field.
Line 2..N+1: N characters with no spaces. 0 represents "ravaged for that block; 1 represents "ready to eat".

SAMPLE INPUT (file range.in)

6
101111
001111
111111
001111
101101
111001

OUTPUT FORMAT

Potentially several lines with the size of the square and the number of such squares that exist. Order them in ascending order from smallest to largest size.

SAMPLE OUTPUT (file range.out)

2 10
3 4
4 1  
题意:给你一个 N x N 的矩阵,判断有多少个 p x p 的矩阵(2<=p<=N),矩阵里面里面只有 1 。
分析:d[i][j] 表示以下标为 i 和 j 结尾的最大满足条件的矩阵,在计算d[i][j]时,可以根据d[i-1][j-1]来计算,具体可以看代码中的 judge;时间复杂度O(n^3)。
这里有个特列
3
111
111
011
View Code
/*
  ID: dizzy_l1
  LANG: C++
  TASK: range
*/
#include<iostream>
#include<cstdio>
#include<cstring>
#define MAXN 260

using namespace std;

int map[MAXN][MAXN],d[MAXN][MAXN],ans[MAXN],n;

int judge(int p,int q)
{
    int i,k,cnt1,cnt2;
    k=d[p-1][q-1];
    cnt1=cnt2=0;
    for(i=p;i>=p-k;i--)
        if(map[i][q]==1)
            cnt1++;
        else break;
    for(i=q;i>=q-k;i--)
        if(map[p][i]==1)
            cnt2++;
        else break;
    return min(cnt1,cnt2);
}

int main()
{
    freopen("range.in","r",stdin);
    freopen("range.out","w",stdout);
    int i,j,k;
    while(scanf("%d",&n)==1)
    {
        memset(d,0,sizeof(d));
        memset(ans,0,sizeof(ans));
        memset(map,0,sizeof(map));
        for(i=1;i<=n;i++)
            for(j=1;j<=n;j++)
                scanf("%1d",&map[i][j]);
        for(i=1;i<=n;i++)
        {
            for(j=1;j<=n;j++)
            {
                if(map[i][j]) d[i][j]=judge(i,j);
                else d[i][j]=0;
            }
        }
        for(i=2;i<=n;i++)
        {
            for(j=2;j<=n;j++)
            {
                for(k=2;k<=d[i][j];k++)
                {
                    ans[k]++;
                }
            }
        }
        for(i=2;i<=n;i++)
            if(ans[i])
                printf("%d %d\n",i,ans[i]);
    }
    return 0;
}
其实还可以用dp的方法求d[i][j]; d[i][j]=min( d[i-1][j-1] , d[i][j-1] , d[i-1][j] );
posted @ 2012-09-15 15:25  mtry  阅读(368)  评论(0)    收藏  举报