【UVA1330】City game

来源:互联网 发布:淘宝卖家被投诉后果 编辑:程序博客网 时间:2024/06/03 20:08

题面

  Bob is a strategy game programming specialist. In his new city building game the gaming environment is as follows: a city is built up by areas, in which there are streets, trees, factories and buildings. There is still some space in the area that is unoccupied. The strategic task of his game is to win as much rent money from these free spaces. To win rent money you must erect buildings, that can only be rectangular, as long and wide as you can. Bob is trying to find a way to build the biggest possible building in each area. But he comes across some problems — he is not allowed to destroy already existing buildings, trees, factories and streets in the area he is building in.
  Each area has its width and length. The area is divided into a grid of equal square units. The rent paid for each unit on which you’re building stands is 3$.
  Your task is to help Bob solve this problem. The whole city is divided into K areas. Each one of the areas is rectangular and has a different grid size with its own length M and width N . The existing occupied units are marked with the symbol ‘R’. The unoccupied units are marked with the symbol ‘F’.

题意

有一个NM的01矩阵,求出最大的全1子矩阵的面积(NM103,多组数据)

解法

DP
  这种矩阵类型的题目有很多,什么最大权值和子矩阵,最大非负子矩阵,平均数最大子矩阵……一大堆
  这种问题一般都是用相似的方法来解决。首先看一下另一道题:

  这道题的要求就是求出最大子矩阵和,考虑来枚举矩阵获得答案
  记录矩阵每一行的前缀和,然后枚举矩阵的左边界l和右边界r,然后枚举第k行,计算出l r内的值x,假设sum表示前面满足条件(非负)的和,那么如果x+sum依旧满足非负,我们就可以去更新答案,否则就重新开始计数,代码如下:

  这与本题十分相似,我们可以对其稍加改动,也同样得到一个O(n3的程序

  这样的复杂度显然是不符合要求的,所以考虑优化
  设fij表示在第i行,第j列,竖直方向上的最长全1串的长度,li表示在当前行的第i列往左最远的不小于fij的位置,ri同理
  然后可以通过类似于KMPNext数组的求法来递推求得liri,接着就更新答案:第i行,第j列能够产生的最大面积就是fijrili+1
  其实二维最大子矩阵和还有其他的求法,这里推荐一篇博客:http://blog.csdn.net/kavu1/article/details/50547401

复杂度

O(NM

代码

#include<algorithm>#include<iostream>#include<cstdlib>#include<cstdio>#define Lint long long intusing namespace std;const int MAXN=1010;int g[MAXN][MAXN],f[MAXN][MAXN];int l[MAXN],r[MAXN];int T,n,m,ans;int main(){    char cs;    scanf("%d",&T);    while( T-- )    {        ans=0;        scanf("%d%d",&n,&m);        for(int i=1;i<=n;i++)            for(int j=1;j<=m;j++)            {                scanf("%c",&cs);                while( cs!='F' && cs!='R' )   cs=getchar();                g[i][j]= cs=='F' ;            }        for(int i=1;i<=n;i++)   for(int j=1;j<=m;j++)   f[i][j]=0;        for(int i=1;i<=n;i++)        {            f[i][0]=f[i][m+1]=-1;            for(int j=1;j<=m;j++)                f[i][j]= g[i][j] ? f[i-1][j]+1 : 0 ;            for(int j=1,x;j<=m;j++)            {                x=j;                while( f[i][j]<=f[i][x-1] )   x=l[x-1];                l[j]=x;            }            for(int j=m,x;j>=1;j--)            {                x=j;                while( f[i][j]<=f[i][x+1] )   x=r[x+1];                r[j]=x;            }            for(int j=1;j<=m;j++)   ans=max( ans,f[i][j]*(r[j]-l[j]+1) );        }        printf("%d\n",ans*3);    }    return 0;}
原创粉丝点击