标签:
Description
An array of size n≤106 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
| 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
Hint
The data used in this problem is unofficial data prepared by love8909. So any mistake here does not imply mistake in the offcial judge data.
给定一个大小已知的数组以及一个大小已知的滑动窗口,窗口每个时刻向后移动一位,求出每个时刻窗口中数字的最大值和最小值。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <vector>
#include <queue>
#include <stack>
#include <map>
#include <algorithm>
#include <set>
using namespace std;
typedef long long ll;
typedef unsigned long long Ull;
#define MM(a,b) memset(a,b,sizeof(a));
const double eps = 1e-10;
const int inf = 0x3f3f3f3f;
const double pi=acos(-1);
const int maxn=1000000;
int a[maxn+10],deq[maxn+10],ans[maxn+10],n,k;
void minq()
{
int s=1,t=0;
for(int i=1;i<=n;i++)
{
while(s<=t&&a[deq[t]]>a[i]) t--;//这个地方加不加等号貌似都可以
deq[++t]=i;
if(i>=k)
{
ans[i-k+1]=a[deq[s]];
if(deq[s]==i-k+1)
s++;
}
}
for(int i=1;i<n-k+1;i++)
printf("%d ",ans[i]);
printf("%d\n",ans[n-k+1]);
}
void maxq()
{
int s=1,t=0;
for(int i=1;i<=n;i++)
{
while(s<=t&&a[deq[t]]<a[i]) t--;
deq[++t]=i;
if(i>=k)
{
ans[i-k+1]=a[deq[s]];
if(deq[s]==i-k+1)
s++;
}
}
for(int i=1;i<n-k+1;i++)
printf("%d ",ans[i]);
printf("%d\n",ans[n-k+1]);
}
int main()
{
while(~scanf("%d %d",&n,&k))
{
for(int i=1;i<=n;i++)
scanf("%d",&a[i]);
minq();
maxq();
}
return 0;
}
CDOJ Sliding Window 线段树(nlogn)或双端队列(n) 模板
标签:
原文地址:http://www.cnblogs.com/smilesundream/p/5447525.html