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)

#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) 贴一个题解 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;
}

猜你喜欢

转载自blog.csdn.net/xiao_k666/article/details/83278779
今日推荐