• 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;
    }
    
  • 相关阅读:
    玩家上线
    小退
    GS发包到MS
    share初始化
    3 水仙花数
    The left-hand side of an assignment must be a variable,代码中使用了中文的字符
    Mac Sublime Text 浏览器 设置快捷键 让html文件在浏览器打开
    2 质数求解
    1 斐波那契的兔子
    18 赛手的名单
  • 原文地址:https://www.cnblogs.com/fusiwei/p/13926032.html
Copyright © 2020-2023  润新知