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;
    }
    
  • 相关阅读:
    CodeForces 452C Magic Trick (排列组合)
    zoj 3209 Treasure Map(精确覆盖)
    POJ 1459 Power Network(网络流 最大流 多起点,多汇点)
    POJ 1273 Drainage Ditches(网络流 最大流)
    HDU Tickets(简单的dp递推)
    ZOJ 3080 ChiBi(spfa)
    URAL 1036(dp+高精度)
    最佳的 清楚浮动 clearfix
    响应式开发
    javascript 性能优化
  • 原文地址:https://www.cnblogs.com/fusiwei/p/13926032.html
Copyright © 2011-2022 走看看