【POJ - 3494 】【Largest Submatrix of All 1’s】

版权声明:本人原创,未经许可,不得转载 https://blog.csdn.net/qq_42505741/article/details/81951919

题目:

Given a m-by-n (0,1)-matrix, of all its submatrices of all 1’s which is the largest? By largest we mean that the submatrix has the most elements.

Input

The input contains multiple test cases. Each test case begins with m and n (1 ≤ mn ≤ 2000) on line. Then come the elements of a (0,1)-matrix in row-major order on mlines each with n numbers. The input ends once EOF is met.

Output

For each test case, output one line containing the number of elements of the largest submatrix of all 1’s. If the given matrix is of all 0’s, output 0.

Sample Input

2 2
0 0
0 0
4 4
0 0 0 0
0 1 1 0
0 1 1 0
0 0 0 0

Sample Output

0
4

题意:给我们一个m*n的全部由0 1 组成的矩阵,问最大的非零矩阵由多少1组成

解题思路:思维转化一下,问的是最大的全1子矩阵 ,所以我们可以转化为每列的最大高度乘以左右比他们稍微大一些的高,转化为面积的求解,最后循环max一下,得到最大解。

ac代码:

扫描二维码关注公众号,回复: 3009363 查看本文章
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<map>
#include<queue>
#include<stack>
#include<cmath>
#define maxn 5050
using namespace std;
int a[maxn][maxn];
int n,m;
int lt[maxn],rt[maxn],ht[maxn];
int main()
{
	int ans,t;
	while(scanf("%d%d",&m,&n)!=EOF)
	{
		for(int i=1;i<=m;i++)
		{
			for(int j=1;j<=n;j++)
				scanf("%d",&a[i][j]);
		}
		ans=0;
		for(int i=1;i<=n;i++)
			ht[i]=0;//初始化列高为0 
		for(int i=1;i<=m;i++)
		{
			ht[0]=ht[n+1]=-1;
			for(int k=1;k<=n;k++)
			{
				if(a[i][k])
					ht[k]++;
				else
					ht[k]=0;
			}
			for(int j=1;j<=n;j++)
			{
				t=j;
				while(ht[t-1]>=ht[j])
					t=lt[t-1];
				lt[j]=t;
			}
			for(int j=n;j>=1;j--)
			{
				t=j;
				while(ht[t+1]>=ht[j])
					t=rt[t+1];
				rt[j]=t;
			}
			for(int j=1;j<=n;j++)
				ans=max(ans,ht[j]*(rt[j]-lt[j]+1));
		}
		cout<<ans<<endl;
	}	
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_42505741/article/details/81951919
今日推荐