单调队列1003 HDU 3530 Subsequence

本文介绍了一种使用双端队列实现的高效算法,该算法用于在一个整数序列中找到满足特定条件的最大长度连续子序列。具体条件是子序列中最大元素与最小元素之差需同时大于等于m且小于等于k。

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

Problem Description

There is a sequence of integers. Your task is to find the longest subsequence that satisfies the following condition: the difference between the maximum element and the minimum element of the subsequence is no smaller than m and no larger than k.

题意:
给一个长度为n的序列,从中找到一个最长的连续的子序列满足
最大的元素和最小的元素的差>=m&&<=k
思路:
维护两个单调队列,维护的时候是维护最大值减去最小值<=ki就行了

#include<stdio.h>
#include<string.h>
#include<iostream>
#include<algorithm>
#include<math.h>
#include<queue>
#include<stack>
#include<string>
#include<vector>
#include<map>
#include<set>
using namespace std;
#define lowbit(x) (x&(-x))
typedef long long LL;
const int maxn = 100005;
const int inf=(1<<28)-1;
deque<pair<int,int> >QueMax,QueMin;
int main()
{
    int n,k,m;
    while(~scanf("%d%d%d",&n,&m,&k))
    {
        int ans=0;
        QueMax.clear();
        QueMin.clear();
        int MinPos=-1;
        for(int i=0;i<n;++i)
        {
            int x;
            scanf("%d",&x);
            while(!QueMax.empty()&&QueMax.back().first<x) QueMax.pop_back();
            while(!QueMin.empty()&&QueMin.back().first>x) QueMin.pop_back();
            QueMax.push_back(make_pair(x,i));
            QueMin.push_back(make_pair(x,i));
            while(!QueMax.empty()&&!QueMin.empty()&&QueMax.front().first-QueMin.front().first>k)
            {
                if(QueMax.front().second>QueMin.front().second)
                {
                    MinPos=QueMin.front().second;
                    QueMin.pop_front();
                }
                else
                {
                    MinPos=QueMax.front().second;
                    QueMax.pop_front();
                }
            }
            if(QueMax.front().first-QueMin.front().first>=m)
            ans=max(ans,i-MinPos);
        }
        printf("%d\n",ans);
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值