二分+单调栈 SPOJ MINSUB

本文介绍了一种使用单调栈求解SPOJ-MINSUB问题的方法,通过两次遍历数组分别统计每个元素向前和向后的延伸长度,进而找到满足条件的最大子矩阵。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:

https://vjudge.net/problem/SPOJ-MINSUB


一开始并不会做,然后看了看下面的题解:

http://blog.youkuaiyun.com/just_sort/article/details/54135267


然后大体思想理解了,之前写单调栈一直都是用stack<node>,node里记录向前延伸向后延伸以及当前的数值和位置,写这个题的时候觉得用这种方法写起来比较麻烦,然后尝试去使用题解中的方法,单调栈可以像这篇题解中使用一个数组来模拟栈,同时分两次遍历数组并统计每个元素的向前延伸和向后延伸,也是一种比较简单的写法。此类题目基本都可以用二分来解决,最后注意二分的取值。


附上代码:

#include <iostream>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <cstring>
#include <vector>
#include <list>
#include <map>
#include <queue>
#include <stack>
#include <bitset>
#include <sstream>
#include <algorithm>
#include <numeric>
#include <functional>
//#include <iomanip.h>
#include <limits.h>
//#include <strstrea.h>
//#include <fstream.h>
#define ll long long
#define ull unsigned long long
//#define int64 long long
#define INF  0x3f3f3f3f

using namespace std;

const int maxn = 1e3 + 5;
int t, n, m, k;
int a[maxn][maxn], b[maxn][maxn], l[maxn][maxn], r[maxn][maxn], st[maxn], top;

int check(int x) {
    int ans = 0;
    for (int j = 1; j <= m; j++) b[1][j] = (a[1][j] >= x);
    for (int i = 2; i <= n; i++) {
        for (int j = 1; j <= m; j++) {
            b[i][j] = (a[i][j] >= x) ? (b[i - 1][j] + 1) : 0;
        }
    }
    for (int i = 1; i <= n; i++) {
        top = st[1] = l[i][1] = 1;
        for (int j = 2; j <= m; j++) {
            while (top > 0 && b[i][st[top]] >= b[i][j]) top--;
            l[i][j] = (top) ? (st[top] + 1) : 1;
            st[++top] = j;
        }
        top = 1;
        st[1] = r[i][m] = m;
        for (int j = m - 1; j >= 1; j--) {
            while (top > 0 && b[i][st[top]] >= b[i][j]) top--;
            r[i][j] = (top) ? (st[top] - 1) : m;
            st[++top] = j;
        }
        for (int j = 1; j <= m; j++) {
            if (b[i][j]) ans = max(ans, b[i][j] * (r[i][j] - l[i][j] + 1));
        }
    }
    return ans;
}

int main() {
    //freopen("in.txt", "r", stdin);
    //freopen("data.out", "w", stdout);
    cin >> t;
    while (t--) {
        cin >> n >> m >> k;
        for (int i = 1; i <= n; i++)
            for (int j = 1; j <= m; j++)
                cin >> a[i][j];
        int l = 0, r = 1e9, mid;
        int mmax;
        while (l < r) {
            mid = (l + r) >> 1;
            if (check(mid) >= k) l = mid + 1, mmax = mid;
            else r = mid;
        }
        cout << mmax << " " << check(mmax) << endl;
    }
    //fclose(stdin);
    //fclose(stdout);
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值