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;
    }
    
  • 相关阅读:
    数据库优化
    2013调试sql的方法
    C++ Primer Pluse_6_课后题
    软件测试--(10)功能测试、系统测试
    软件测试--发展之路
    软件测试--(9)软件测试过程和软件测试模型
    软件测试--(8)软件开发过程和软件开发模型
    软件测试--(7)集成测试
    软件测试--(6)模块测试(单元测试)
    软件测试--(5)测试策略
  • 原文地址:https://www.cnblogs.com/fusiwei/p/13926032.html
Copyright © 2011-2022 走看看