51Nod 1158 - 全是1的最大子矩阵(DP)

题目链接 http://www.51nod.com/onlineJudge/questionCode.html#!problemId=1158

【题目描述】
给出1个M*N的矩阵M1,里面的元素只有0或1,找出M1的一个子矩阵M2,M2中的元素只有1,并且M2的面积是最大的。输出M2的面积。

Input
第1行:2个数m,n中间用空格分隔(2 <= m,n <= 500)
第2 - N + 1行:每行m个数,中间用空格分隔,均为0或1。
Output
输出最大全是1的子矩阵的面积。

Input示例
3 3
1 1 0
1 1 1
0 1 1
Output示例
4

【思路】
依然当成最大子矩阵和来做,只不过需要判断一下当前矩阵是不是全1的即可,复杂度是 O ( n 3 ) O(n^3) O(n3)

#include<bits/stdc++.h>
using namespace std;

const int maxn=505;

int n,m;
int g[maxn][maxn];

int main(){
	scanf("%d%d",&m,&n);
	for(int i=1;i<=n;++i){
		for(int j=1;j<=m;++j){
			scanf("%d",&g[i][j]);
			g[i][j]+=g[i-1][j];
		}
	}
	int ans=0;
	for(int i=1;i<=n;++i){
		for(int j=i;j<=n;++j){
			int cnt=0;
			for(int k=1;k<=m;++k){
				if(g[j][k]-g[i-1][k]!=j-i+1){
					ans=max(ans,cnt*(j-i+1));
					cnt=0;
				}
				else ++cnt;
			}
			ans=max(ans,cnt*(j-i+1));
		}
	}
	printf("%d\n",ans);
	return 0;
}

这题可以借助单调栈优化到 O ( n 2 ) O(n^2) O(n2) 贴一个题解 51Nod 1158

#include<bits/stdc++.h>
using namespace std;

const int maxn=505;

int n,m;
int g[maxn][maxn],h[maxn][maxn];
int le[maxn],ri[maxn];
stack<int> st;

int main(){
	scanf("%d%d",&m,&n);
	for(int i=1;i<=n;++i){
		for(int j=1;j<=m;++j){
			scanf("%d",&g[i][j]);
			if(g[i][j]) h[i][j]=h[i-1][j]+1;
		}
	}

	int ans=0;
	for(int i=1;i<=n;++i){
		while(st.size()) st.pop();
		for(int j=1;j<=m;++j){
			while(st.size() && h[i][st.top()]>=h[i][j]) st.pop();
			if(st.empty()) le[j]=-1;
			else le[j]=st.top();
			st.push(j);
		}
		while(st.size()) st.pop();
		for(int j=m;j>=1;--j){
			while(st.size() && h[i][st.top()]>=h[i][j]) st.pop();
			if(st.empty()) ri[j]=-1;
			else ri[j]=st.top();
			st.push(j);
		}
		
		for(int j=1;j<=m;++j){
			int len;
			if(le[j]==-1 && ri[j]==-1) len=m;
			else if(le[j]==-1) len=ri[j]-1;
			else if(ri[j]==-1) len=m-le[j];
			else len=ri[j]-le[j]-1;
			ans=max(ans,len*h[i][j]);
		}
	}
	printf("%d\n",ans);

	return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值