【单调队列】第十四届蓝桥杯省赛C++ C组 Java C组/研究生组 Python A组《子矩阵》(C++)

【题目描述】

给定一个 n×m (n 行 m 列)的矩阵。

设一个矩阵的价值为其所有数中的最大值和最小值的乘积。

求给定矩阵的所有大小为 a×b (a 行 b 列)的子矩阵的价值的和。

答案可能很大,你只需要输出答案对 998244353 取模后的结果。

【输入格式】

输入的第一行包含四个整数分别表示 n,m,a,b,相邻整数之间使用一个空格分隔。

接下来 n 行每行包含 m 个整数,相邻整数之间使用一个空格分隔,表示矩阵中的每个数

【输出格式】

输出一行包含一个整数表示答案。

【数据范围】

对于 40% 的评测用例,1≤n,m≤100;

对于 70% 的评测用例,1≤n,m≤500;

对于所有评测用例,1≤a≤n≤1000,1≤b≤m≤1000,1≤Ai,j≤

【输入样例】

2 3 1 2
1 2 3
4 5 6

【输出样例】

58

【样例解释】

1×2+2×3+4×5+5×6=58。

【代码】

cpp 复制代码
#include <iostream>
#include <cstring>
#include <algorithm>

using namespace std;

typedef long long LL;
const int N = 1010, MOD = 998244353;

int n, m, A, B;
int w[N][N];
int rmax[N][N], rmin[N][N];
int q[N];

void get_max(int a[], int b[], int tot, int k)
{
    int hh = 0, tt = -1;
    for (int i = 0; i < tot; i ++ )
    {
        if (hh <= tt && q[hh] <= i - k) hh ++ ;
        while (hh <= tt && a[q[tt]] <= a[i]) tt -- ;
        q[ ++ tt] = i;
        b[i] = a[q[hh]];
    }
}

void get_min(int a[], int b[], int tot, int k)
{
    int hh = 0, tt = -1;
    for (int i = 0; i < tot; i ++ )
    {
        if (hh <= tt && q[hh] <= i - k) hh ++ ;
        while (hh <= tt && a[q[tt]] >= a[i]) tt -- ;
        q[ ++ tt] = i;
        b[i] = a[q[hh]];
    }
}

int main()
{
    scanf("%d%d%d%d", &n, &m, &A, &B);
    for (int i = 0; i < n; i ++ )
        for (int j = 0; j < m; j ++ )
            scanf("%d", &w[i][j]);

    for (int i = 0; i < n; i ++ )
    {
        get_max(w[i], rmax[i], m, B);
        get_min(w[i], rmin[i], m, B);
    }

    int res = 0;

    int a[N], b[N], c[N];
    for (int i = B - 1; i < m; i ++ )
    {
        for (int j = 0; j < n; j ++ ) a[j] = rmax[j][i];
        get_max(a, b, n, A);
        for (int j = 0; j < n; j ++ ) a[j] = rmin[j][i];
        get_min(a, c, n, A);
        for (int j = A - 1; j < n; j ++ )
            res = (res + (LL)b[j] * c[j]) % MOD;
    }

    printf("%d\n", res);
    return 0;
}
相关推荐
小灰灰爱代码32 分钟前
C++——求3*3矩阵对角元素之和。
数据结构·c++·算法
老K(郭云开)40 分钟前
allWebPlugin中间件自定义alert、confirm及prompt使用
c++·chrome·中间件·prompt·html5·edge浏览器
福鸦3 小时前
详解c++:new和delete
开发语言·c++
createcrystal4 小时前
《算法笔记》例题解析 第3章入门模拟--3图形输出(9题)2021-03-03
c++·笔记·算法
我要学编程(ಥ_ಥ)4 小时前
双指针算法专题(2)
数据结构·算法·leetcode
逸狼4 小时前
【JavaEE初阶】多线程6(线程池\定时器)
java·开发语言·算法
no_play_no_games5 小时前
[模板]树的最长路径
算法·深度优先·图论·树形结构
tan77º5 小时前
【C++】异常
c++·算法
ymchuangke5 小时前
数据清洗-缺失值处理-缺失值可视化图(竖线)
python·算法·数学建模
我要学编程(ಥ_ಥ)6 小时前
滑动窗口算法专题(1)
java·数据结构·算法·leetcode