子矩阵(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);
}
相关推荐
啊哦呃咦唔鱼4 分钟前
LeetCode hot100-438 找到字符串中所以字母异位词
算法·leetcode·职场和发展
重生之后端学习10 分钟前
136. 只出现一次的数字
开发语言·算法·leetcode·职场和发展·深度优先
见叶之秋14 分钟前
详解单链表(含链表的实现过程)
数据结构·链表
smj2302_7968265233 分钟前
解决leetcode第3869题.统计区间内奇妙数的数目
python·算法·leetcode
witAI33 分钟前
**Sora仿真人剧2025推荐,解锁沉浸式互动叙事新体验*
c++
CodeCraft Studio35 分钟前
Parasoft C/C++嵌入式软件测试解决方案:安全、可靠且符合标准
开发语言·c++·安全·单元测试·代码规范·parasoft·嵌入式软件测试
TracyCoder1231 小时前
LeetCode Hot100(66/100)——118. 杨辉三角
算法·leetcode·职场和发展
葳_人生_蕤1 小时前
Leetcode HOT 100
算法·leetcode·职场和发展
仟濹1 小时前
【算法打卡day23(2026-03-15 周日)今日算法or技巧:双指针 & 链表 & 回溯算法】6个题
数据结构·算法·链表
跃龙客1 小时前
C++写文件笔记
c++·笔记