POJ 2823 Sliding Window

本文介绍了一种使用单调队列解决滑动窗口中最大值与最小值问题的方法。该问题要求在一个长度为n的数组中寻找大小为k的滑动窗口在每个位置上的最大值和最小值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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?'\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

 

转载于:https://www.cnblogs.com/crackpotisback/p/4738009.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值