Description
Long time ago, a king occupied a vast territory. Now there is a problem that he worried that he want to choose a largest square of his territory to build a palace. Can you help him? For simplicity, we use a matrix to represent the territory as follows: 0 0 0 0 0 0 1 0 1 0 1 1 1 1 0 0 1 1 0 0 0 0 1 0 0 Every single number in the matrix represents a piece of land, which is a 1*1 square 1 represents that this land has been occupied 0 represents not Obviously the side-length of the largest square is 2Input
The first line of the input contains a single integer t (1≤t≤5) — the number of cases. For each case The first line has two integers N and M representing the length and width of the matrix Then M lines follows to describe the matrix 1≤N,M≤1000Output
For each case output the the side-length of the largest squareSample Input
2 5 5 0 0 0 0 0 0 1 0 1 0 1 1 0 1 0 0 1 1 0 0 0 0 1 0 0 5 5 0 0 0 0 0 0 1 0 1 0 1 1 1 1 0 0 1 1 0 0 0 0 1 0 0Sample Output
1 2
我的思路:和上一道单调栈的题一样,只不过这次要一行一行来处理,因为问题不同吗。不是很理解的话,去看看代码吧!
下面附上代码:
#include<cstdio>
#include<cstring>
#include<cmath>
#include<climits>
#include<string>
#include<queue>
#include<stack>
#include<iostream>
#include<map>
#include<vector>
#include<algorithm>
using namespace std;
#define ll long long
struct node
{
int height;
int startindex;
node(int _height, int _index):height(_height), startindex(_index){};
};
int main()
{
int T;
scanf("%d", &T);
while(T--)
{
int mp[1010], currentposition, currentarea, maxarea = 0, N, M, x, height1;
scanf("%d%d", &N, &M);
for(int i = 1; i <= N; i++)
{
for(int j = 1; j <= M; j++)
{
scanf("%d", &x);
if(x)
mp[j]++;
else
mp[j]=0;
}
stack<node> s;
s.push(node(-1, 0));
for(int j = 1; j < M+2; j++)
{
currentposition = j;
if(j == M+1)
height1 = 0;
else
height1 = mp[j];
node cur(height1, currentposition);
while(height1<s.top().height)
{
cur = s.top();
s.pop();
if((currentposition-cur.startindex)==cur.height)
currentarea = cur.height;
maxarea = max(maxarea, currentarea);
}
s.push(node(height1, cur.startindex));
}
}
printf("%d\n", maxarea);
}
}