一、滑动窗口
给定一个大小为 n≤1e6 的数组。
有一个大小为 k 的滑动窗口,它从数组的最左边移动到最右边。
你只能在窗口中看到 k 个数字。
每次滑动窗口向右移动一个位置。
以下是一个例子:
该数组为 [1 3 -1 -3 5 3 6 7]
,k 为 3。
窗口位置 | 最小值 | 最大值 |
---|---|---|
[1 3 -1] -3 5 3 6 7 | -1 | 3 |
1 [3 -1 -3] 5 3 6 7 | -3 | 3 |
1 3 [-1 -3 5] 3 6 7 | -3 | 5 |
1 3 -1 [-3 5 3] 6 7 | -3 | 5 |
1 3 -1 -3 [5 3 6] 7 | 3 | 6 |
1 3 -1 -3 5 [3 6 7] | 3 | 7 |
你的任务是确定滑动窗口位于每个位置时,窗口中的最大值和最小值。
输入格式
输入包含两行。
第一行包含两个整数 n 和 k,分别代表数组长度和滑动窗口的长度。
第二行有 n 个整数,代表数组的具体数值。
同行数据之间用空格隔开。
输出格式
输出包含两个。
第一行输出,从左至右,每个位置滑动窗口中的最小值。
第二行输出,从左至右,每个位置滑动窗口中的最大值。
输入样例:
8 3
1 3 -1 -3 5 3 6 7
输出样例:
-1 -3 -3 -3 3 3
3 3 5 5 6 7
#include<iostream>
#include<algorithm>
#define N 1000010
using namespace std;int n,k;
int arr[N],q[N];//q队列所存储的为下标
int main(){cin>>n>>k;for(int i=0;i<n;i++){cin>>arr[i];}int hh=0,tt=-1;//队列的头尾指针for(int i=0;i<n;i++){if(i+1-k>q[hh]) hh++;//如果头指针不在窗口内,就丢掉while(hh<=tt&&arr[q[tt]]>=arr[i]) tt--;q[++tt]=i;if(i+1>=k) cout<<arr[q[hh]]<<" ";//求的是最小值}cout<<endl;hh=0,tt=-1;for(int i=0;i<n;i++){if(i+1-k>q[hh]) hh++;//如果头指针不在窗口内,就丢掉while(hh<=tt&&arr[q[tt]]<=arr[i]) tt--;//注意这里变成"<="q[++tt]=i;if(i+1>=k) cout<<arr[q[hh]]<<" ";//求的是最大值}return 0;
}
二、子矩阵
给定一个 n×m (n 行 m 列)的矩阵。设一个矩阵的价值为其所有数中的最大值和最小值的乘积。求给定矩阵的所有大小为 a×b (a 行 b列)的子矩阵的价值的和。
答案可能很大,你只需要输出答案对 998244353取模后的结果。
输入格式
输入的第一行包含四个整数分别表示 n,m,a,b,相邻整数之间使用一个空格分隔。
接下来 n行每行包含 m个整数,相邻整数之间使用一个空格分隔,表示矩阵中的每个数 Ai,j
输出格式
输出一行包含一个整数表示答案。
数据范围
对于 40%40% 的评测用例,1≤n,m≤100
对于 70%70% 的评测用例,1≤n,m≤500
对于所有评测用例,1≤a≤n≤1000,1≤b≤m≤1000,1≤Ai,j≤1e9
输入样例:
2 3 1 2
1 2 3
4 5 6
输出样例:
58
样例解释
1×2+2×3+4×5+5×6=581×2+2×3+4×5+5×6=58。
分析:
其实和滑动窗口差不多,关键在于把二维变成一维
#include<iostream>
#include<algorithm>
#define N 1010
#define MOD 998244353
typedef long long LL;
using namespace std;int n,m,A,B;
int w[N][N];
int rmin[N][N],rmax[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(){cin>>n>>m>>A>>B;for(int i=0;i<n;i++){for(int j=0;j<m;j++){cin>>w[i][j];}}for(int i=0;i<n;i++){get_max(w[i],rmax[i],m,B);//第一行里面在B长度的移动下,将单调递减序列存入rmax[]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++){//以B的长度开始移动for(int j=0;j<n;j++) a[j]=rmax[j][i];get_max(a,b,n,A);//用数组b来接受最大值for(int j=0;j<n;j++) a[j]=rmin[j][i];get_min(a,c,n,A);//用数组c来接受最小值for(int j=A-1;j<n;j++){res=(res+(LL)b[j]*c[j])%MOD;}}cout<<res;return 0;
}