第一周任务Largest Submatrix of All 1’s
2024-10-07 19:25:25
Largest Submatrix of All 1’s
Time Limit: 5000MS | Memory Limit: 131072K | |
Total Submissions: 9512 | Accepted: 3406 | |
Case Time Limit: 2000MS |
Description
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 ≤ m, n ≤ 2000) on line. Then come the elements of a (0,1)-matrix in row-major order on m lines 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
Source
思路:
这道题是二维数组,跟上一道题多了一维,那么我们就一行遍历,求一行中最大的矩形,再行遍历的时候就更新最大矩形面积。
代码:(数组)
#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;
typedef long long ll;
const int maxn = 2e3+;
int a[maxn][maxn];
int L[maxn],R[maxn];
int st[maxn];
int main(){
int m,n;
while(scanf("%d%d",&m,&n)!=EOF){
for(int i=;i<=n;i++)
a[][i] = ;
for(int i=;i<=m;i++){
for(int j=;j<n;j++){
scanf("%d",&a[i][j]);
if(a[i][j]!=)
a[i][j] = a[i][j] +a[i-][j]; //这里是关键
}
} int res = ;
for(int i=;i<=m;i++){
memset(st,,sizeof(st));
int t = ;
for(int j=;j<n;j++){
while(t>&&a[i][st[t-]]>=a[i][j]) t--;
L[j] = t==?:(st[t-]+);
st[t++] = j;
}
t=;
for(int j = n-;j>=;j--){
while(t>&&a[i][st[t-]]>=a[i][j]) t--;
R[j] = t==?n:(st[t-]);
st[t++] = j;
}
for(int j=;j<n;j++){
res=max(res,a[i][j]*(R[j]-L[j]));
}
}
cout<<res<<endl;
}
return ;
}
代码2:栈
#include<iostream>
#include<stdio.h>
#include<string.h>
#include<stack>
using namespace std;
typedef long long ll;
const int maxn = 2e3+;
int a[maxn][maxn];
stack<int> s;
int main(){
int m,n;
while(cin>>m&&cin>>n){
for(int i=;i<=m;i++)
a[][i] = ;
for(int i=;i<=m;i++){
for(int j=;j<=n;j++){
scanf("%d",&a[i][j]);
if(a[i][j]!=)
a[i][j] = a[i-][j]+;
}
}
ll res = ;
for(int i=;i<=m;i++){
while(!s.empty()) s.pop();
int j = ;
while(j<=n+){
if(s.empty()||a[i][s.top()]<=a[i][j])
s.push(j++);
else{
int t=s.top();
s.pop();
ll wid = s.empty()?(j-):(j-s.top()-);
res = max(res,wid*a[i][t]);
}
}
}
cout<<res<<endl;
}
return ;
}
最新文章
- ★Kali信息收集~2.Whois :域名信息
- 资源搜集:Git精品文章推荐,常年更新
- Jmeter—8 连接microsoft sql server数据库取数据
- C语言 const常量讲解
- Unity3D独立游戏开发日记(一):动态生成树木
- POJ 1523 SPF tarjan求割点
- Parse_ini_file
- java从命令行接收多个数字,求和之后输出结果
- hold
- 还是把一个课程设计作为第一篇文章吧——学生学籍管理系统(C语言)
- 线程、线程句柄、线程ID
- Sql server中Collation conflict问题
- PHP中实现异步调用多线程程序代码
- python entry points 例子
- 使用Hamcrest增强JUnit的测试能力
- 确保 PHP 应用程序的安全 -- 不能违反的四条安全规则
- 2015&;nbsp;Objective-C&;nbsp;三大新特性
- JdbcUtil
- 用flask实现的分页
- 【tomcat】Web环境(tomcat)下新增一个访问路径(虚拟路径)