Subsequence
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 4903 Accepted Submission(s): 1615
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.
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.
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
问最长的一个子序列长度是多少,子序列满足最大值减去最小值在m和k之间。
用两个队列,最大值队列和最小值队列,最大值队列单调递减,最小值队列单调递增,最大值队列里的点u表示从u开始到当前点的最大值是a[u],最小值队列里的点u表示从u开始到当前点的最小值是a[u]。一旦最大值队列首元素的值和最小值队列首元素的值之差不大于k,就判断这两个值的差是否不小于m,是就更新答案,注意更新答案的长度是从两个队列队首上个点加1里面大的那个值到当前点这段长度。如果最大值队列首元素的值和最小值队列首元素的值之差大于k,就把靠前的那个front加1,再继续判断。要注意细节问题,我为了方便处理先在队首加了个权值INF的点。
用单调队列处理后复杂度是O(N)。
#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<vector>
#include<cmath>
#include<queue>
#include<stack>
#include<map>
#include<set>
#include<algorithm>
#pragma comment(linker, "/STACK:102400000,102400000")
using namespace std;
typedef long long LL;
const LL MAXN=100010;
const LL MAXM=5010;
const LL INF=0x3f3f3f3f;
int N,M,K;
int a[MAXN],q1[MAXN],q2[MAXN];
int main(){
freopen("in.txt","r",stdin);
while(scanf("%d%d%d",&N,&M,&K)!=EOF){
for(int i=1;i<=N;i++) scanf("%d",&a[i]);
a[0]=INF;
int front1=0,rear1=0,front2=0,rear2=0;
q1[0]=q2[0]=0;
int ans=0;
for(int i=1;i<=N;i++){
while(front1<=rear1&&a[q1[rear1]]<=a[i]) rear1--;
q1[++rear1]=i;
while(front2<=rear2&&a[q2[rear2]]>=a[i]) rear2--;
q2[++rear2]=i;
while(a[q1[front1]]-a[q2[front2]]>K){
if(q1[front1]<q2[front2]) front1++;
else front2++;
}
if(a[q1[front1]]-a[q2[front2]]>=M){
if(front2<=0) ans=max(ans,i-q1[front1-1]);
ans=max(ans,i-max(q1[front1-1],q2[front2-1]));
}
}
printf("%d\n",ans);
}
return 0;
}