51nod 1158 全是1的最大子矩陣 單調棧

題目鏈接:

http://www.51nod.com/onlineJudge/questionCode.html#!problemId=1158

題意:

給出個的矩陣,裏面的元素只有0或1,找出M1的一個子矩陣,M1中的元素只有1,並且的面積是最大的。輸出的面積

題解:

單調棧,把每一列數看成一個數組。

代碼:

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define MS(a) memset(a,0,sizeof(a))
#define MP make_pair
#define PB push_back
const int INF = 0x3f3f3f3f;
const ll INFLL = 0x3f3f3f3f3f3f3f3fLL;
inline ll read(){
    ll x=0,f=1;char ch=getchar();
    while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
    while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
    return x*f;
}
//////////////////////////////////////////////////////////////////////////
const int maxn = 1e5+10;

int a[505][505],f[505][505];

struct node{
    int v,pre,nxt;
    node(int v) : v(v),pre(1),nxt(1) {}
};

int main(){
    int n,m;
    cin >> n >> m;
    for(int i=1; i<=n; i++)
        for(int j=1; j<=m; j++)
            cin >> a[i][j];

    MS(f);
    for(int i=1; i<=n; i++)
        for(int j=1; j<=m; j++)
            if(a[i][j]) f[i][j] = f[i][j-1] + 1; // 每一位置可以向左拓展幾個
    ll ans = -1; 
    for(int j=1; j<=m; j++){ // 對每一列數進行一次單調棧的拓展
        stack<node> s;
        s.push(node(f[1][j]));
        for(int i=2; i<=n; i++){
            node t(f[i][j]);
            while(!s.empty() && t.v<=s.top().v){ // 出現比棧頂小的行數,就要彈出,因爲已經不能向後拓展了
                node tt = s.top(); s.pop();
                if(!s.empty()) s.top().nxt += tt.nxt; // 向後拓展

                t.pre += tt.pre; // 向前拓展
                ll tmp = tt.v * (tt.pre+tt.nxt-1); // 計算矩形的面積
                if(ans < tmp)
                    ans = tmp;
            }
            s.push(t);
        }
        while(!s.empty()){
            node tt = s.top(); s.pop();
            if(!s.empty()) s.top().nxt += tt.nxt;
            ll tmp = tt.v * (tt.pre+tt.nxt-1);
            if(ans < tmp)
                ans = tmp;
        }
    }

    cout << ans << endl;



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