HDU 2830 Matrix Swapping II(最大完全子矩阵之可移动列)

来源:互联网 发布:html中如何加入js类 编辑:程序博客网 时间:2024/05/01 18:53

题目链接:Click here~~

题意:

给你一个矩阵,里面的数字只有0和1两种,其中,列可以任意移动。问如何移动可以使某个子矩阵中元素全部是1,求出这个最大子矩阵的面积。

解题思路:

枚举所有的尾行,然后对于每个尾行,记录到这行为止每列连续的1的个数,为了形象起见,我们可以把每列看做宽度为1,连续个数看做它的高度。

然后问题就可以看做在一些高度可能为0的相邻矩形中找到最大矩形,即最大长方形那道题,如下图。


此题的另外一个条件是可以将列任意移动,我们肯定要尽量将高度大的放在一起,所以,我们可以将高度从大到小排序,然后有h[i-1]>=h[i],

即如果将1,2…i个矩形连在一起,它的高应该是h[i],所以面积显然是h[i] * i。

然后我们就枚举i从1到n,就可以解决这个问题了。

#include <stdio.h>#include <string.h>#include <algorithm>using namespace std;bool cmp(int a,int b){    return a > b;}int main(){    int R,C,num[1005],a[1005];    while(~scanf("%d%d",&R,&C))    {        getchar();        int ans = 0;        memset(num,0,sizeof(num));        for(int i=1;i<=R;i++)        {            for(int j=1;j<=C;j++)            {                char c = getchar();                if(c == '1')                    ++num[j];                else                    num[j] = 0;                a[j] = num[j];            }            sort(a+1,a+1+C,cmp);            for(int j=1;j<=C && a[j];j++)                if(a[j]*j > ans)                    ans = a[j]*j;            getchar();        }        printf("%d\n",ans);    }    return 0;}


原创粉丝点击