Time limit12000 ms Case time limit5000 ms Memory limit65536 kBOSLinux
An array of size n ≤ 10 6 is given to you. There is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves rightwards by one position. Following is an example: The array is [1 3 -1 -3 5 3 6 7], and k is 3. Window position Minimum value Maximum value [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 Your task is to determine the maximum and minimum values in the sliding window at each position.
Input The input consists of two lines. The first line contains two integers n and k which are the lengths of the array and the sliding window. There are n integers in the second line. Output There are two lines in the output. The first line gives the minimum values in the window at each position, from left to right, respectively. The second line gives the maximum values. Sample Input 8 3 1 3 -1 -3 5 3 6 7 Sample Output -1 -3 -3 -3 3 3 3 3 5 5 6 7
题意:给定一个长度为n(n<=10^6)的序列和一个整数k,求长度为k的子序列中的最小值并依次输出,最大值也依次输出
分析:n的范围为[1,10^6],不可能依次枚举 这里用到了 双端队列的思想 拿找最小值举例: 先加入一个,后面加入一个数,如果这个数比队列中的数要小,就把队尾的数删掉,直到队尾的数比要加入的数小,在此基础上,如果队列中已经有k个数,删掉队头
#include<cstdio> #include<cstring> #include<algorithm> using namespace std; const int N=1e6+5; int n,k; int dq[N],ans[N],a[N]; int dq2[N],ans2[N]; void solve() { int s=0,t=0; int s2=0,t2=0; for(int i=0; i<n; i++) { while(s<t&&a[dq[t-1]]>=a[i])//队尾的数大于要加入的数 ,找最大值和最小值部分一样 t--; dq[t++]=i;//将第i+1个数加入队列 if(i-k+1>=0)///若队列中有k个数那么就记录最小值 ans[i-k+1]=a[dq[s]]; if(dq[s]==i-k+1)///队列中的数大于k个 s++; while(s2<t2&&a[dq2[t2-1]]<=a[i])///小于 t2--; dq2[t2++]=i; if(i-k+1>=0) ans2[i-k+1]=a[dq2[s2]]; if(dq2[s2]==i-k+1) s2++; //printf("dq2[%d]=%d\n",t2-1,dq2[t2-1]); } for(int i=0; i<=n-k; i++) printf("%d%c",ans[i],i==n-k?'\n':' '); for(int i=0; i<=n-k; i++) printf("%d%c",ans2[i],i==n-k?'\n':' '); } int main() { while(~scanf("%d%d",&n,&k)) { for(int i=0; i<n; i++) scanf("%d",&a[i]); solve(); } return 0; }