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;
    }
    
  • 相关阅读:
    Mysql基本操作
    MySql架构
    并发中关键字的语义
    SpringMVC<一> 基本结构与配置
    Tomcat 顶层结构
    Linux 日常常用指令
    JSON 数据格式
    RMAN 增量备份级别说明
    Oracle常用数据库系统表单以及SQL的整理
    使用puTTY或Xshell连接阿里云TimeOut超时
  • 原文地址:https://www.cnblogs.com/fusiwei/p/13926032.html
Copyright © 2011-2022 走看看