POJ 3494 Largest Submatrix of All 1’s 單調棧(數組版)

題目鏈接:POJ 3494


代碼如下:

// 數組模擬stack版
#include <utility>
#include <cstring>
#include <cstdio>
using namespace std;

#define fi first
#define se second
const int N = 2002;
typedef pair<int, int> pii;
int mat[N][N], a[N]; // from 1 to n / [1, n]

struct monotone_stack
{
    pii sk[N]; // first = startpos, second = index of a[]
    int mx[N], topPtr, m;   // mx = max rectangle area through a[i] , m = max(mx[])
    // 棧底元素下標爲0,值爲0
    void clear() {
        m = -(int)1e9;
        topPtr = 1;
        sk[0].fi = 0, sk[0].se = 0;
    }
    void push(int x) {
        while(topPtr) {
            pii t = sk[topPtr-1];
            if(a[t.se] > a[x]) {
                mx[t.se] = (x - t.fi) * a[t.se];
                if(m < mx[t.se]) m = mx[t.se];
                topPtr--;
            }
            else break;
        }
        if(a[sk[topPtr-1].se] == a[x]) sk[topPtr] = pii(sk[topPtr-1].fi, x);
        else sk[topPtr] = pii(sk[topPtr-1].se + 1, x);
        ++topPtr;
    }
    void solve(int x) {  // x is the (end + 1) index of a[]
        while(topPtr) {
            pii t = sk[topPtr-1];
            mx[t.se] = (x - t.fi) * a[t.se];
            if(m < mx[t.se]) m = mx[t.se];
            topPtr--;
        }
    }
    int segm() { return m; }
} s;

int main()
{
    // freopen("in", "r", stdin);
    int n, m;
    while(~scanf("%d%d", &m, &n)) {
        memset(a, 0, sizeof(a));
        int ans = 0, t;
        for(int i = 1; i <= m; ++i) {
            s.clear();
            for(int j = 1; j <= n; ++j) {
                scanf("%d", mat[i] + j);
                a[j] = mat[i][j] ? a[j] + 1 : 0;
                s.push(j);
            }
            s.solve(n + 1);
            if(ans < (t = s.segm())) ans = t;
        }
        printf("%d\n", ans);
    }
    return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章