题目描述:
思路:单调队列。 先用单调队列解决“滑动窗口”类问题的思路,求出每行的大小为b的“窗口”内的最大值与最小值。再用两个单调队列求出每a个"窗口"的最大值和最小值。
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
#define int long long
#define ios ios::sync_with_stdio(false); cin.tie(0);cout.tie(0)
const int N = 1e3+5;
const int mod = 998244353;
int n, m1, a, b;
int m[N][N];
deque<int > q1[N], q2[N];
deque<int > mx, mi;
void solve(){
cin >> n >> m1 >> a >> b;
for(int i = 1; i <= n; i++){
for(int j = 1; j <= m1; j++){
cin >> m[i][j];
}
}
int ans = 0;
for(int j = 1; j <= m1; j++){
for(int i = 1; i <= n; i++){
if(q1[i].empty()){
q1[i].push_back(j);
}else{
while(!q1[i].empty() && j - q1[i].front() + 1 > b){
q1[i].pop_front();
}
while(!q1[i].empty() && m[i][j] >= m[i][q1[i].front()]){
q1[i].pop_front();
}
q1[i].push_back(j);
}
if(q2[i].empty()){
q2[i].push_back(j);
}else{
while(!q2[i].empty() && j - q2[i].front() + 1> b){
q2[i].pop_front();
}
while(!q2[i].empty() && m[i][j] <= m[i][q2[i].front()]){
q2[i].pop_front();
}
q2[i].push_back(j);
}
//cout << "i : " << i <<" j :" << j << endl;
//cout << q1[i].front() <<" " << q2[i].front() << endl;
if(j >= b){
if(mx.empty()){
mx.push_back(i);
}else{
while(!mx.empty() && i - mx.front() + 1 > a){
mx.pop_front();
}
while(!mx.empty() && m[i][q1[i].front()] >= m[mx.front()][q1[mx.front()].front()]){
mx.pop_front();
}
mx.push_back(i);
}
if(mi.empty()){
mi.push_back(i);
}else{
while(!mi.empty() && i - mi.front() + 1 > a) {
mi.pop_front();
}
while(!mi.empty() && m[i][q2[i].front()] <= m[mi.front()][q2[mi.front()].front()]){
mi.pop_front();
}
mi.push_back(i);
}
if(i >= a){
int k1 = m[mx.front()][q1[mx.front()].front()];
int k2 = m[mi.front()][q2[mi.front()].front()];
//cout << k1 <<" " << k2 << endl;
ans += k1*k2%mod;
ans %= mod;
}
}
}
mx.clear(), mi.clear();
}
cout << ans << endl;
}
signed main(){
ios; int _;
_ = 1; //cin >> _;
while(_--){
solve();
}
return 0;
}