2019牛客多校第八场——A. All-one Matrices【单调栈/思维】【不可扩大的全1子矩阵个数】

链接:https://ac.nowcoder.com/acm/contest/888/A

题目描述

Gromah and LZR entered the great tomb, the first thing they see is a matrix of size n×mn\times mn×m, and the elements in the matrix are all 00_{}0​ or 11_{}1​.

LZR finds a note board saying "An all-one matrix is defined as the matrix whose elements are all 11_{}1​, you should determine the number of all-one submatrices of the given matrix that are not completely included by any other all-one submatrices".

Meanwhile, Gromah also finds a password lock, obviously the password should be the number mentioned in the note board!

Please help them determine the password and enter the next level.

输入描述:

The first line contains two positive integers n,mn,m_{}n,m​, denoting the size of given matrix.

Following nn_{}n​ lines each contains a string with length mm_{}m​, whose elements are all 00_{}0​ or 11_{}1​, denoting the given matrix.

1≤n,m≤30001\le n,m \le 30001≤n,m≤3000

输出描述:

Print a non-negative integer, denoting the answer.

输入

3 4
0111
1110
0101

输出

5

说明

The 5 matrices are (1,2)−(1,4),  (1,2)−(2,3),  (1,2)−(3,2),  (2,1)−(2,3),  (3,4)−(3,4)(1,2)-(1,4), \; (1,2)-(2,3), \; (1,2)-(3,2), \; (2,1)-(2,3), \; (3,4)-(3,4)_{}(1,2)−(1,4),(1,2)−(2,3),(1,2)−(3,2),(2,1)−(2,3),(3,4)−(3,4)​.

题意:

给你一个01矩阵,求出所有不可扩大的全1矩阵的个数;

分析:

对于每一个[i,j],记录从它开始向上连续的1的个数num;

枚举每一行作为矩阵底边所在行,从前向后枚举每一列,维护一个num单调上升的栈,对于栈中每一个num值,还要维护一个该num对应位置向左最远能扩展到的位置pos;

元素出栈时,设该元素是(num,pos),那么可以得到一个全1矩阵(i-num+1,pos)->(i,j);

此时该矩阵最左为pos已经记录(不可向左扩展),向上最多为num已经记录(不可向上扩展),因为大于当前num才出栈(不可向右扩展),所以只要判定能否向下扩展,如果不能,那么这就是一个答案矩阵。

#include
using namespace std;
const int maxn=3007;
char s[maxn][maxn];
int num[maxn][maxn];
stack< pair > S;
int main()
{
	int n,m;scanf("%d%d",&n,&m);getchar();
	for (int i=1;i<=n;i++)
	{
		for (int j=1;j<=m;j++) scanf("%c",&s[i][j]);
		getchar();
	}
	for (int i=1;i<=n;i++)
		for (int j=1;j<=m;j++)
			num[i][j]=(s[i][j]=='1')?num[i-1][j]+1:0;
	int ans=0;
    for (int i=1;i<=n;i++)
    {
    	int tmp=-1;
    	while (!S.empty()) S.pop();
    	for (int j=1;j<=m+1;j++)
    	{
    		int pos=j;
    		while (!S.empty() && S.top().first>num[i][j])
	    	{
	    		if(S.top().second<=tmp) ans++;//下一行中[pos,j]中有0存在 不可向下扩展
	    		pos=S.top().second;
	    		S.pop();
	    	}
	    	if(!num[i+1][j]) tmp=j;//记录下一行中截至当前最右边0的位置
	    	if(num[i][j] && (S.empty() || S.top().first

 

你可能感兴趣的:(数据结构,单调栈,思维,2019牛客多校)