poj 3494 Largest Submatrix of All 1’s 单调栈/DP迭代法
2016-07-10 23:56
489 查看
题意:给出一个m*n的01矩阵,问在系数全为1的子矩阵中 系数和的最大值。
解法:DP中的迭代法,或者单调栈。
不论哪种方法核心都是对于每个高度为h的矩形,找到最左高度大于等于它的位置,和最右的位置。
#include<cstdio>
#include<string>
#include<cstring>
#include<iostream>
#include<cmath>
#include<algorithm>
#include<vector>
using namespace std;
#define all(x) (x).begin(), (x).end()
#define for0(a, n) for (int (a) = 0; (a) < (n); (a)++)
#define for1(a, n) for (int (a) = 1; (a) <= (n); (a)++)
typedef long long ll;
typedef pair<int, int> pii;
const int INF =0x3f3f3f3f;
const int maxn= 2000 ;
struct Node
{
int h;
int le;
};
int n,m,ans;
int h[maxn+10];
Node sta[maxn+10];
int main()
{
while(~scanf("%d%d",&m,&n))
{
int x,ans=0;
memset(h,0,(n+1)*sizeof h[0]);
for1(i,m)
{
int top=0;
for1(j,n)
{
scanf("%d",&x);
if(!x) h[j]=0;
else h[j]++;
if(top&&sta[top].h>h[j])
{
while(top&&sta[top].h>h[j])
{
ans=max(ans, sta[top].h*(j-sta[top].le) );
top--;
}
sta[++top].h=h[j];
}
else
{
sta[++top].h=h[j];
sta[top].le=j;
if(top>=2&&sta[top-1].h==sta[top].h ) sta[top].le=sta[top-1].le;
}
}
while(top)
{
ans=max(ans,sta[top].h*( n+1- sta[top].le) );
top--;
}
}
printf("%d\n",ans);
}
return 0;
}
/*
4 4
1 0 0 0
1 1 1 1
0 1 1 1
1 0 0 1
*/
解法:DP中的迭代法,或者单调栈。
不论哪种方法核心都是对于每个高度为h的矩形,找到最左高度大于等于它的位置,和最右的位置。
#include<cstdio>
#include<string>
#include<cstring>
#include<iostream>
#include<cmath>
#include<algorithm>
#include<vector>
using namespace std;
#define all(x) (x).begin(), (x).end()
#define for0(a, n) for (int (a) = 0; (a) < (n); (a)++)
#define for1(a, n) for (int (a) = 1; (a) <= (n); (a)++)
typedef long long ll;
typedef pair<int, int> pii;
const int INF =0x3f3f3f3f;
const int maxn= 2000 ;
struct Node
{
int h;
int le;
};
int n,m,ans;
int h[maxn+10];
Node sta[maxn+10];
int main()
{
while(~scanf("%d%d",&m,&n))
{
int x,ans=0;
memset(h,0,(n+1)*sizeof h[0]);
for1(i,m)
{
int top=0;
for1(j,n)
{
scanf("%d",&x);
if(!x) h[j]=0;
else h[j]++;
if(top&&sta[top].h>h[j])
{
while(top&&sta[top].h>h[j])
{
ans=max(ans, sta[top].h*(j-sta[top].le) );
top--;
}
sta[++top].h=h[j];
}
else
{
sta[++top].h=h[j];
sta[top].le=j;
if(top>=2&&sta[top-1].h==sta[top].h ) sta[top].le=sta[top-1].le;
}
}
while(top)
{
ans=max(ans,sta[top].h*( n+1- sta[top].le) );
top--;
}
}
printf("%d\n",ans);
}
return 0;
}
/*
4 4
1 0 0 0
1 1 1 1
0 1 1 1
1 0 0 1
*/
相关文章推荐
- 图解微服务架构演进
- Java应用架构的演化之路
- 面试题29:数组中出现次数超过一半的数字
- 热烈庆祝杨学明老师为北京某著名互联网金融公司提供三天的辅导与培训服务!
- Linux入门---创建新用户
- springMvc工作流程图
- 数据库和JDBC编程
- 成为Java GC专家(4)—Apache的MaxClients参数详解及其在Tomcat执行FullGC时的影响
- Javascript学习系列(六):javascript控制Cookie,保留用户登录信息
- 再谈网游同步技术:实时动作游戏同步方式和传输协议选择
- 安卓中无限轮播的实现
- 四种常用的排序算法(冒泡、选择、倒序、插入)
- STL序列式容器之list(双向链表)
- System V 信号量机制
- 成为Java GC专家(3)—如何优化Java垃圾回收机制
- chrome使用技巧
- java面试宝典学习笔记(三)
- 自定义控件—Scroller屏幕平缓滑动工具类
- 谈谈Js闭包的那些事儿
- # android studio使用遇到的问题