Subsequence

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.
有一个整数序列。 您的任务是查找满足以下条件的最长子序列: 子序列的最大元素和最小元素之间的差不小于 m,也不大于 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.
有多个测试案例。对于每个测试案例,第一行有三个整数,n,m 和 k。 n 是序列的长度,在范围[1,100000]。 M 和 k 在0,1000000的范围内。 第二行有 n 个整数,都在[0,1000000]范围内。
进入文件结束处。

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

解题思路

我们用两个单调队列 一个单调递增 一个单调递减
通过一个变量存储序列起始位置,然后再通过一些特判修改起始位置
最后在过程中得出i-起始位置+1的各个值,找到最大的结果

AC代码

#include<algorithm>
#include<iostream>
#include<cstdio>
#include<cmath>
using namespace std;
long long n,m,k,o,op,head1,head2,tail1,tail2,a[1000005],b1[1000005],b2[1000005],q1[1000005],q2[1000005],p1[1000005],p2[1000005];
int main()
{
   
	while(scanf("%lld%lld%lld",&n,&m,&k)!=EOF)
	{
   
		for(int i=1;i<=n;i++)
	 	 scanf("%lld",&a[i]);
		op=head1=head2=1;//初值
		o=tail1=tail2=0;
		for(int i=1;i<=n;i++)
		{
   
			while(a[i]<a[p1[tail1]]&&head1<=tail1)tail1--;//单调递增
			p1[++tail1]=i;
		
			while(a[p2[tail2]]<a[i]&&head2<=tail2)tail2--;//单调递减
			p2[++tail2]=i;
			
			while(a[p2[head2]]-a[p1[head1]]>k)//如果超了k
			 if(p1[head1]<p2[head2])op=p1[head1++]+1;//就更新o
			 else op=p2[head2++]+1;
			if(a[p2[head2]]-a[p1[head1]]>=m)o=max(o,i-op+1); //找最大值
		} 
		cout<<o<<endl;
	}
	return 0;
}

谢谢