qscoj#19D(单调队列)

本文介绍了一个利用单调栈解决滑动窗口最大值问题的算法实现。通过具体的代码示例,详细展示了如何使用单调栈来高效地求解给定数组中每个窗口的最大值。

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

题目链接:http://qscoj.cn/problem/130/

 

题意:中文题诶~

 

思路:直接用单调栈搞一下就好了

 

代码:

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 
 4 const int MAXN=1e6+10;
 5 const int inf=1e9;
 6 int sum[MAXN], q[MAXN];
 7 
 8 int main(void){
 9     int n, k;
10     while(scanf("%d%d", &n, &k)!=EOF){
11         for(int i=1; i<=n; i++){
12             int x;
13             scanf("%d", &x);
14             sum[i]=sum[i-1]+x;
15         }
16         sum[n+1]=-inf;
17         int ans=0, front=0, rear=0;
18         for(int i=1; i<=n+1; i++){
19             ans=max(ans, sum[i]);
20             if((front==rear||sum[i]>sum[q[front]])){
21                 if(i-q[rear+1]+1<k){
22                     q[++front]=i;
23                 }else{
24                     while(i-q[rear+1]+1>=k&&front>rear){
25                         rear++;
26                     }
27                     q[++front]=i;
28                 }
29             }else if(sum[i]<sum[q[front]]){
30                 while(front>rear&&sum[i]<sum[q[front]]){
31                     ans=max(ans, sum[q[front]]-sum[q[rear+1]]);
32                     front--;
33                 }
34                 while(i-q[rear+1]+1>=k&&front>rear){
35                     rear++;
36                 }
37                 q[++front]=i;
38             }
39         }
40         printf("%d\n", ans);
41     }
42     return 0;
43 }
View Code

 

转载于:https://www.cnblogs.com/geloutingyu/p/6834242.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值