1. 程式人生 > >單調棧 求最大子矩陣的大小

單調棧 求最大子矩陣的大小

#include<iostream>
#include<stdio.h>
#include<stack>
using namespace std;
template<class T>
int length(T& arr)
{
    return sizeof(arr) / sizeof(arr[0]);
}
int maxRecFromBottom(int myheight[], int x)
{
    int height[5];
    for(int i = 0; i < x; i++)
    {
        height[i] = myheight[i];
    }

    int mylength = length(height);
    if(mylength == 0)
    {
        return 0;
    }
    int maxArea = 0;
    stack<int> s1;
    for(int i = 0; i < mylength; i++)
    {
        while(!s1.empty() && height[i] <= height[s1.top()])
        {
            //下標為i的數想要挑戰單調棧棧頂
            int cur1 = s1.top();//單調棧棧頂的值(當前待處理值)
            s1.pop();
            int cur2 = s1.empty() ? -1 : s1.top();//當前待處理值的下一個值
        int curArea = (i - cur2 - 1) * height[cur1];
        maxArea = curArea > maxArea ? curArea : maxArea;
        }
        s1.push(i);
    }
    while(!s1.empty())
    {
        int j = s1.top();
         s1.pop();
        int k = s1.empty() ? -1 : s1.top();
        int curArea = (mylength - k - 1) * height[j];
        maxArea = curArea > maxArea ? curArea : maxArea;
    }
    return maxArea;
}
int maxRecSize(int mymap[][4], int x, int y)
{
    int maxArea = 0;
    int height[y] = {0};
    for(int i = 0; i < x; i++)
    {
        for(int j = 0; j < y; j++)
        {
            cout<< height[j]<<" ";
            height[j] = mymap[i][j] == 0 ? 0 : height[j] + 1;

        }
        cout<<endl;

        maxArea = maxRecFromBottom(height, y) > maxArea ? maxRecFromBottom(height, y) : maxArea;
    }
    return maxArea;
}
int main()
{
    //1011
    //1111
    //1110
    int x;
    cin>>x;
    int myans[x][4];
    for(int i = 0; i < x; i++)
    {
        for(int j = 0; j < 4; j++)
        {
            cin>>myans[i][j];
        }
    }
    int ans = maxRecSize(myans, x, 4);
    cout<<ans;
    return 0;
}