1. 程式人生 > >51Nod 1158 - 全是1的最大子矩陣(DP)

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;
}