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.
Sample Input
5 0 0
1 1 1 1 1
5 0 3
1 2 3 4 5
Sample Output
5
4
题目分析:
题目大意是在一长串数字列中找出最长字串并且其最大值与最小值在指定范围内,
这样,可以构造两个单调递减队列和单调递增数列,分别记录当前字串中的最大值
和最小值,当这两个值的差在指定范围内时与ans进行比较,从此得出最大的ans,
复杂度大概为O(n)级别的
代码:
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
int n,m,k,i,head1,head2,rear1,rear2,ans,now;
int a[100005],l[100005],r[100005];
while (~scanf("%d%d%d",&n,&m,&k))
{
head1=head2=rear1=rear2=0;
ans=0;
now=1;
for (i=1;i<=n;i++)
{
scanf("%d",&a[i]);
while (head1<rear1&&a[l[rear1-1]]>a[i]) rear1--; //构造递增队列,头指针指向对象最小
while (head2<rear2&&a[r[rear2-1]]<a[i]) rear2--; //构造递减队列,头指针指向对象最大
l[rear1++]=i;
r[rear2++]=i;
while (head1<rear1&&head2<rear2&&a[r[head2]]-a[l[head1]]>k) //最大值与最小值之差大于k则调整头指针
{
if (l[head1]<r[head2]) now=l[head1++]+1;
else now=r[head2++]+1;
}
if (head1<rear1&&head2<rear2&&a[r[head2]]-a[l[head1]]>=m)
{
if (ans<i-now+1) ans=i-now+1;
}
}
printf("%d\n",ans);
}
return 0;
}
#include <cstring>
using namespace std;
int main()
{
int n,m,k,i,head1,head2,rear1,rear2,ans,now;
int a[100005],l[100005],r[100005];
while (~scanf("%d%d%d",&n,&m,&k))
{
head1=head2=rear1=rear2=0;
ans=0;
now=1;
for (i=1;i<=n;i++)
{
scanf("%d",&a[i]);
while (head1<rear1&&a[l[rear1-1]]>a[i]) rear1--; //构造递增队列,头指针指向对象最小
while (head2<rear2&&a[r[rear2-1]]<a[i]) rear2--; //构造递减队列,头指针指向对象最大
l[rear1++]=i;
r[rear2++]=i;
while (head1<rear1&&head2<rear2&&a[r[head2]]-a[l[head1]]>k) //最大值与最小值之差大于k则调整头指针
{
if (l[head1]<r[head2]) now=l[head1++]+1;
else now=r[head2++]+1;
}
if (head1<rear1&&head2<rear2&&a[r[head2]]-a[l[head1]]>=m)
{
if (ans<i-now+1) ans=i-now+1;
}
}
printf("%d\n",ans);
}
return 0;
}