POJ——3494 Largest Submatrix of All 1’s(思维题,求第一大全1矩阵)

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

意:求第一大全1矩阵

题解:用dp[i][j]表示这个位置,往上延伸最多有多少个连续的1,结构体存的是矩形的高 和 宽的左边坐标,然后暴力一行一行找~~

感觉会超时,结果没超时,还贼快~~

上代码:(此代码max1是第一大,max2是第二大,所以第一大,第二大都能求~~哈哈~~)

#include <iostream>
#include <cstdio>
using namespace std;
const int MAX = 2e3+400;
int max1,max2,top;//max1是第一大的值,max2是第二大的值
struct hh{
	int l,h;
	hh(int _l=0,int _h=0):l(_l),h(_h){}
}q[MAX];
int dp[MAX][MAX],s[MAX][MAX];
void update(int x){
	if(x>=max1){
		max2=max1;
		max1=x;
	}
	else if(x>max2){
		max2=x;
	}
}
int main(){
	int n,m;
	while(~scanf("%d%d",&n,&m)){
		max1=max2=0;
		for (int i = 1; i <= n;i++){
			for (int j = 1; j <= m;j++){
				scanf("%1d",&dp[i][j]);
				s[i][j]=dp[i][j];
				dp[i][j]+=dp[i][j]*dp[i-1][j];//保存向上延伸最多有多少个1
			}
		}
		for (int i = 1; i <= n;i++){
			top=0;
			for (int j = 1; j <= m;j++){
				if(s[i][j]==0) top=0;//有一个是0,就要重新开始找,前面无法再包括进去,只能往后找
				else{
					int tmp=j;
					while(q[top].h>dp[i][j]&&top) tmp=q[top--].l;//找到宽符合是全1矩阵的位置
					if(q[top].h!=dp[i][j]) q[++top]=hh(tmp,dp[i][j]);
					for (int k = 1; k <= top;k++){
						update(q[k].h*(j-q[k].l+1));//更新最大、第二大的值
					}
				}
			}
		}
		printf("%d\n",max1);//输出第一大的值
	}	
	return 0;
} 

 

全部评论

相关推荐

马上要带我人生中的第一个实习生了,想问问大家都喜欢什么的mentor?好让我有个努力的目标
拒绝996的劳伦斯很勇敢:看得见目标且护犊子的 具体就是明确告诉组员要干什么,然后当别的组甩dirty work时能护的组自家新人
点赞 评论 收藏
分享
05-05 21:45
已编辑
广州大学 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务