HDU3530 Subsequence

本文介绍了一种算法,用于寻找整数序列中最长的子序列,该子序列的最大元素与最小元素之差介于给定区间内。通过使用两个单调队列来高效地解决问题。

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

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.

Input

There are multiple test cases.
For each test case, the first line has three integers, n, m and k. n is the length of the sequence and is in the range [1, 100000]. m and k are in the range [0, 1000000]. The second line has n integers, which are all in the range [0, 1000000].
Proceed to the end of file.

Output

For each test case, print the length of the subsequence on a single line.

思路

我们对于一个所有数都>=0的序列,显然就是求连续的序列,那么我们枚举右端点,然后2个单调队列解决,如果最大最小值之差>R,当然要去掉最大,最小值最前面的哪一个(显然更优)
code:

#include<iostream>
#include<algorithm>
#include<cstring>
#include<deque>
#include<cstdio>
#include<map>
using namespace std;
unsigned long long a[100001];
deque<unsigned long long> mx,mn;
unsigned long long f[100001],s[100001];
unsigned long long t,v,r,c,b,x,l,j,k,L,R;
unsigned long long n,p,u,i,m,ans;
void read(unsigned long long& x)
{
 x=0;
 unsigned long long f=1;
 char ch=getchar();
 while (!isdigit(ch)) (ch=='-')&&(f=-1),ch=getchar();
 while (isdigit(ch)) x=(x<<1)+(x<<3)+(ch^48),ch=getchar();
 x*=f;
}
void wr(unsigned long long x)
{
 (x<0)&&(x=-x,putchar('-'));
 if (x>9) wr(x/10);
 putchar(x%10^48);
}
int main()
{
 while (cin>>n>>L>>R)
 {
  ans=0;
  u=0;
  mx.clear();
  mn.clear();
  for (int i=1;i<=n;i++)
  {
   read(a[i]);
   while (mx.size()&&a[mx.back()]<a[i]) mx.pop_back();
   mx.push_back(i);
   while (mn.size()&&a[mn.back()]>a[i]) mn.pop_back();
   mn.push_back(i);
   while (mx.size()&&mn.size()&&a[mx.front()]-a[mn.front()]>R)
   {
    if (mx.front()<mn.front()) u=mx.front(),mx.pop_front();
    else u=mn.front(),mn.pop_front();
   }
   if (mx.size()&&mn.size()&&a[mx.front()]-a[mn.front()]>=L) ans=max(ans,i-u);
  }
  wr(ans);
  printf("\n");
 }
 return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值