【NOIP2015模拟10.22】最大子矩阵

Description

我们将矩阵A中位于第i行第j列的元素记作A[i,j]。一个矩阵A是酷的仅当它满足下面的条件:
A[1,1]+A[r,s]<=A[1,s]+A1”>r,1
其中r为矩阵A的行数,s为矩阵A的列数。
进一步,如果一个矩阵是非常酷的仅当它的每一个至少包含两行两列子矩阵都是酷的。
你的任务是,求出一个矩阵A中的一个非常酷的子矩阵B,使得B包含最多元素。

Input

第一行包含两个整数R,S(2<=R,S<=1000),代表矩阵的行数与列数。
接下来R行每行包括S个整数,代表矩阵中的元素,矩阵中元素的绝对值不大于1000000。

Output

一行一个整数,代表子矩阵B的元素总数。如果没有一个非常酷的子矩阵,输出0。

Sample Input

输入1:
3 3
1 4 10
5 2 6
11 1 3
输入2:
3 3
1 3 1
2 1 2
1 1 1
输入3:
5 6
1 1 4 0 3 3
4 4 9 7 11 13
-3 -1 4 2 8 11
1 5 9 5 9 10
4 8 10 5 8 8

Sample Output

输出1:
9
输出2:
4
输出3:
15
【样例3解释】
在第三个样例中,子矩阵B的左上角为A[3,2],右下角为A[5,6]。

Data Constraint

对于60%的数据,满足R,S<=350。
对于100%的数据,满足2<=R,S<=1000,矩阵中元素的绝对值不大于1000000。

思路

显然对于任意一个2*2矩阵我们判断其合法或非法很容易,合法记为1非法记为0。
然后这个图变成了一个只有01构成的,0代码障碍物。题意转换为求最大矩形面积,用经典单调栈做法即可。

代码

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
const int maxn=1077;
int n,m,a[maxn][maxn],s[maxn],tot=0,up[maxn][maxn],ass=0;
int main()
{
    scanf("%d%d",&n,&m);
    for(int i=1; i<=n; i++) for(int j=1; j<=m; j++)
    {
        scanf("%d",&a[i][j]); up[i][j]=1;
    }
    for(int j=2; j<=m; j++) for(int i=2; i<=n; i++)
    {
        if(a[i-1][j-1]-a[i-1][j]<=a[i][j-1]-a[i][j]) up[i][j]=up[i-1][j]+1;
    }
    for(int i=1; i<=n; i++) for(int j=1; j<=m; j++) if(up[i][j]==1) up[i][j]=0;
    s[0]=1;
    for(int i=2; i<=n; i++)
    {
        tot=0;
        for(int j=2; j<=m; j++)
        {
            while(tot&&up[i][j]<=up[i][s[tot]])
            {
                ass=max(ass,up[i][s[tot]]*(j-s[--tot])); //printf("%d\n",ass);
            }
            s[++tot]=j;
        }
        while(tot)
        {
            ass=max(ass,up[i][s[tot]]*(m+1-s[--tot])); //printf("%d\n",ass);
        }
    }
    printf("%d",ass);
}

猜你喜欢

转载自blog.csdn.net/eric1561759334/article/details/81005522
今日推荐