@xunuo
2017-01-16T13:57:00.000000Z
字数 1773
阅读 1105
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
单调队列
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.
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, print the length of the subsequence on a single line.
5 0 0
1 1 1 1 1
5 0 3
1 2 3 4 5
5
4
题意:
第一行输入三个数:n,a,b;
接下来输入n个数
题目意思是让你在序列a[n]中找出一个最长序列,使其最大值与最小值之差在[a,b]之间,问这个序列最长是多少;
解题思路:
利用两个单调队列,一个求最大值,一个求最小值,最大值-最小值要在[a,b]区间内;
完整代码:
#include<stdio.h>
#include<string.h>
#include<queue>
#include<algorithm>
using namespace std;
///队列单减:从头到尾依次递减,头大尾小;
///队列单增:从头到尾依次递增,头小尾大;
int f[100010];
int qmax[100010],head1,tail1;///单减队列,维护最大值
int qmin[100010],head2,tail2;///单增队列,维护最小值
int main()
{
int n,a,b,ans,head;
while(scanf("%d%d%d",&n,&a,&b)!=EOF)
{
memset(f,0,sizeof(f));
memset(qmax,0,sizeof(qmax));
memset(qmin,0,sizeof(qmin));
head1=head2=0;
tail1=tail2=0;
ans=0,head=0;
for(int i=0;i<n;i++)
{
scanf("%d",&f[i]);
while(head1<tail1&&f[i]-f[qmax[tail1-1]]>=0)///利用单减队列维护最大值
tail1--;
while(head2<tail2&&f[i]-f[qmin[tail2-1]]<=0)///利用单增队列维护最小值
tail2--;
qmax[tail1]=i; qmin[tail2]=i;
tail1++; tail2++;
while(head1<tail1&&head2<tail2&&f[qmax[head1]]-f[qmin[head2]]>b)///他们的差大于所给的值后
{
///用一个head来记录目前满足该条件的头的值
if(qmax[head1]<qmin[head2])
{
head=qmax[head1];
head1++;
}
else
{
head=qmin[head2];
head2++;
}
head++;
}
if(head1<tail1&&head2<tail2&&f[qmax[head1]]-f[qmin[head2]]>=a)///他们的差>=所给的值时,求ans
{
ans=max(ans,i-head+1);///要求最长的序列
}
}
printf("%d\n",ans);
}
return 0;
}