2019牛客暑期多校训练营(第八场)A All-one Matrices(单调栈)

题目链接

题解:

先求出每列与每行的前缀和,然后逐行计算答案。

具体的,枚举每行每个点,单调栈求出以该点往上的高度往左往右能够扩展的左右边界 L 和 R。然后判断该点下一行的 L 到 R 之间是不是都被 1 占满,如果不是,则答案加一。

由于每个矩形底边的元素都会重复计算一次,则用哈希去重即可。

代码:

#include <bits/stdc++.h>
using namespace std;

typedef long long ll;
typedef unsigned long long ull;
#define int ll
#define PI acos(-1.0)
#define INF 0x3f3f3f3f3f3f3f3f
#define P pair<int, int>
#define fastio ios::sync_with_stdio(false), cin.tie(0)
const int mod = 998244353;
const int M = 1000000 + 10;
const int N = 3000 + 10;

int n, m;
int a[N][N];
stack<int> st;
unordered_map<int, int> mp;
int pre[N][N], ans;

signed main()
{
    fastio;
    cin >> n >> m;
    for(int i = 1; i <= n; i ++) {
        string s; cin >> s; s = '0' + s;
        for(int j = 1; j <= m; j ++) {
            if(s[j] == '1') {
                a[i][j] = a[i - 1][j] + 1;
                pre[i][j] = 1;
            }
            pre[i][j] += pre[i][j - 1];
        }
    }

    for(int i = 1; i <= n; i ++) {
        while(st.size()) st.pop();
        int l[N], r[N];
        a[i][0] = a[i][m + 1] = -INF;
        for(int j = 1; j <= m + 1; j ++) {
            while(st.size() && a[i][j] < a[i][st.top()]) r[st.top()] = j - 1, st.pop();
            st.push(j);
        }
        while(st.size()) st.pop();
        for(int j = m; j >= 0; j --) {
            while(st.size() && a[i][j] < a[i][st.top()]) l[st.top()] = j + 1, st.pop();
            st.push(j);
        }
        mp.clear();
        for(int j = 1; j <= m; j ++) {
            if(a[i][j] && (r[j] - l[j] + 1) != pre[i+1][r[j]] - pre[i+1][l[j]-1] && mp[l[j]] != r[j]) {
                ans ++;
                mp[l[j]] = r[j];
            }
        }
    }
    cout << ans << endl;

    return 0;
}

/*

  Rejoicing in hope, patient in tribulation.

*/

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值