[关闭]
@xunuo 2017-01-16T05:57:00.000000Z 字数 1773 阅读 1032

Subsequence


Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)

单调队列

链接:HDU 3530 Subsequence


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.

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

题意:

第一行输入三个数:n,a,b;
接下来输入n个数
题目意思是让你在序列a[n]中找出一个最长序列,使其最大值与最小值之差在[a,b]之间,问这个序列最长是多少;

解题思路:

利用两个单调队列,一个求最大值,一个求最小值,最大值-最小值要在[a,b]区间内;

完整代码:

  1. #include<stdio.h>
  2. #include<string.h>
  3. #include<queue>
  4. #include<algorithm>
  5. using namespace std;
  6. ///队列单减:从头到尾依次递减,头大尾小;
  7. ///队列单增:从头到尾依次递增,头小尾大;
  8. int f[100010];
  9. int qmax[100010],head1,tail1;///单减队列,维护最大值
  10. int qmin[100010],head2,tail2;///单增队列,维护最小值
  11. int main()
  12. {
  13. int n,a,b,ans,head;
  14. while(scanf("%d%d%d",&n,&a,&b)!=EOF)
  15. {
  16. memset(f,0,sizeof(f));
  17. memset(qmax,0,sizeof(qmax));
  18. memset(qmin,0,sizeof(qmin));
  19. head1=head2=0;
  20. tail1=tail2=0;
  21. ans=0,head=0;
  22. for(int i=0;i<n;i++)
  23. {
  24. scanf("%d",&f[i]);
  25. while(head1<tail1&&f[i]-f[qmax[tail1-1]]>=0)///利用单减队列维护最大值
  26. tail1--;
  27. while(head2<tail2&&f[i]-f[qmin[tail2-1]]<=0)///利用单增队列维护最小值
  28. tail2--;
  29. qmax[tail1]=i; qmin[tail2]=i;
  30. tail1++; tail2++;
  31. while(head1<tail1&&head2<tail2&&f[qmax[head1]]-f[qmin[head2]]>b)///他们的差大于所给的值后
  32. {
  33. ///用一个head来记录目前满足该条件的头的值
  34. if(qmax[head1]<qmin[head2])
  35. {
  36. head=qmax[head1];
  37. head1++;
  38. }
  39. else
  40. {
  41. head=qmin[head2];
  42. head2++;
  43. }
  44. head++;
  45. }
  46. if(head1<tail1&&head2<tail2&&f[qmax[head1]]-f[qmin[head2]]>=a)///他们的差>=所给的值时,求ans
  47. {
  48. ans=max(ans,i-head+1);///要求最长的序列
  49. }
  50. }
  51. printf("%d\n",ans);
  52. }
  53. return 0;
  54. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注