子矩阵(c++实现)

题目


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

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

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

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


输入


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

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


输出


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


样例


输入样例:

2 3 1 2

1 2 3

4 5 6


输出样例:

58


CODE

c++ 复制代码
#include<iostream>
using namespace std;
const int N = 1010,MOD = 998244353;
int w[N][N];
int n,m,A,B;
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 && i-k>=q[hh]) 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 && i-k>=q[hh]) 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 + (long long)b[j]*c[j])%MOD;
        }
    }
    printf("%d",res);
}
相关推荐
ysu_03146 小时前
05 | 持久化撤销提示非核心功能
算法·游戏程序
浮沉9877 小时前
二分查找算法概述&通用模板
算法
Keven_118 小时前
算法札记:SPFA判负环算法的证明
算法
什巳8 小时前
JAVA练习278- 和为 K 的子数组
java·学习·算法·leetcode
Jerry8 小时前
LeetCode 347. 前 K 个高频元素
算法
Young Doro9 小时前
SAC 算法
线性代数·算法·机器学习
罗超驿9 小时前
2.算法效率的核心密码:时间复杂度和空间复杂度详解
java·数据结构·算法
:-)9 小时前
算法-堆排序
数据结构·算法·排序算法