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
题意:让我们找到一个最长子序列,使得这个子序列中的最大值和最小值相差不超过k不小于m。
思路:通过大佬的思路发现是维护了两个队列,一个是以当前结束所构成的递减序列的位置,另一个是以当前结束构成的递增序列的位置,然后每次的最大值减去最小值,如果大于k,那么就更新两个中的一个,应该更新位置较小的那个,这样才能使得这个区间的长度最大,然后就这么更新就行了 。
AC代码:
#include <bits/stdc++.h>
const int maxx=100010;
const int inf=0x3f3f3f3f;
using namespace std;
int a[maxx],b[maxx],c[maxx];
int main()
{
int n,m,k;
while(~scanf("%d%d%d",&n,&m,&k))
{
for(int i=1; i<=n; i++)
scanf("%d",&a[i]);
int liftl=0,liftt=0,rightr=0,rightt=0,ans=0,pos=0;
for(int i=1; i<=n; i++)
{
while(liftl<rightr && a[b[rightr-1]]<a[i])
rightr--;
while(liftt<rightt && a[c[rightt-1]]>a[i])
rightt--;
b[rightr++]=i;
c[rightt++]=i;
while(liftl<rightr && liftt<rightt && a[b[liftl]]-a[c[liftt]]>k)
{
if(b[liftl]<c[liftt])
pos=b[liftl++];
else
pos=c[liftt++];
}
if(liftl<rightr && liftt<rightt && a[b[liftl]]-a[c[liftt]]>=m)
ans=max(ans,i-pos);
}
printf("%d\n",ans);
}
return 0;
}