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

    Sliding Window

    Time Limit: 12000ms
    Memory Limit: 65536KB
    This problem will be judged on PKU. Original ID: 2823
    64-bit integer IO format: %lld      Java class name: Main
     
    An array of size n ≤ 106 is given to you. There is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers 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], and k is 3.
     
    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
    

    Source

     
    解题:单调队列,太JB卡时间了,需要使用MS C++提交
     
     1 #include <cstdio>
     2 #include <cctype>
     3 using namespace std;
     4 const int maxn = 2000010;
     5 int n,k,d[maxn],q[maxn<<1];
     6 inline bool xiao(int a,int b) {
     7     return a <= b;
     8 }
     9 inline bool da(int a,int b) {
    10     return a >= b;
    11 }
    12 inline bool scan_d(int &num) {
    13     bool IsN = false;
    14     char in = getchar();
    15     if(in == EOF) return false;
    16     while(in != '-' && !isdigit(in)) in = getchar();
    17     if(in == '-') {
    18         IsN = true;
    19         num = 0;
    20     } else num = in - '0';
    21     while((in = getchar()) && isdigit(in)) num = num*10 + in - '0';
    22     if(IsN) num = -num;
    23     return true;
    24 }
    25 void solve(bool (*f)(int,int)) {
    26     int hd = 0,tl = 0;
    27     for(int i = 0; i < n; ++i) {
    28         while(hd < tl && q[hd] + k - 1 < i) hd++;
    29         while(hd < tl && f(d[i],d[q[tl-1]])) tl--;
    30         q[tl++] = i;
    31         if(i + 1 >= k) printf("%d%c",d[q[hd]],i + 1 == n?'
    ':' ');
    32     }
    33 }
    34 int main() {
    35     scanf("%d%d",&n,&k);
    36     for(int i = 0; i < n; ++i)
    37         scan_d(d[i]);
    38     solve(xiao);
    39     solve(da);
    40     return 0;
    41 }
    View Code
  • 相关阅读:
    Python中利用xpath解析HTML
    常见聚类算法——K均值、凝聚层次聚类和DBSCAN比较
    格式化字符串format函数
    编程语言这个垂直方向
    CLR,GC 表示什么意思?
    ASP.Net MVC开发基础学习笔记:一、走向MVC模式
    NPOI 通过excel模板写入数据并导出
    SQL 注意事项
    解决微信公众号OAuth出现40029(invalid code,不合法的oauth_code)的错误
    iis 站点中文乱码 解决方案
  • 原文地址:https://www.cnblogs.com/crackpotisback/p/4738009.html
Copyright © 2011-2022 走看看