zoukankan      html  css  js  c++  java
  • POJ 2823 Sliding Window

    POJ 2823 Sliding Window

    Description

    An array of size 6is given to you. There is a sliding window of sizekwhich is moving from the very left of the array to the very right. You can only see theknumbers 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]

    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
    

    题解:

    滑动窗口。

    代码:

    #include<cstdio>
    #include<deque>
    using namespace std;
    const int maxn=1e6+6;
    int n,k;
    int a[maxn];
    deque<pair<int,int> > q;
    int main()
    {
    	scanf("%d%d",&n,&k);
    	for(int i=1;i<=n;i++)
    		scanf("%d",&a[i]);
    	for(int i=1;i<=n;i++)
    	{
    		while(!q.empty() && a[i]<q.back().second)
    			q.pop_back();
    		q.push_back(make_pair(i,a[i]));
    		while(q.front().first<=i-k)
    			q.pop_front();
    		if(i>=k)
    			printf("%d ",q.front().second);
    	}
    	puts("");
    	q.clear();
    	for(int i=1;i<=n;i++)
    	{
    		while(!q.empty() && a[i]>q.back().second)
    			q.pop_back();
    		q.push_back(make_pair(i,a[i]));
    		while(q.front().first<=i-k)
    			q.pop_front();
    		if(i>=k)
    			printf("%d ",q.front().second);
    	}
    	puts("");
    	return 0;
    }
    
  • 相关阅读:
    阿里Java开发规约【摘录】
    JavaWeb【八、JSP指令与动作元素】
    JavaWeb【七、JSP状态管理】
    JavaWeb【六、JavaBean】
    JavaWeb【五、内置对象】
    JavaWeb【四、JSP基础语法】
    JavaWeb【三、Web程序编写】
    JavaWeb【二、Tomcat安装】
    Django 模板层
    Django auth模块
  • 原文地址:https://www.cnblogs.com/fusiwei/p/13926032.html
Copyright © 2011-2022 走看看