HDU 3530 Subsequence(单调队列)

http://acm.hdu.edu.cn/showproblem.php?pid=3530

题意:

给出一串序列,求出最长的序列,要求该序列内的最大值-最小值在[m,k]之间。

思路:

维护一个单调递增队列和一个单调递减队列。

 1 #include<cstdio>
 2 #include<algorithm>
 3 using namespace std;
 4 const int maxn = 100000+5;
 5 
 6 int n,m,k;
 7 int q1[maxn],q2[maxn],a[maxn];
 8 
 9 int main()
10 {
11     //freopen("in.txt","r",stdin);
12     while(~scanf("%d%d%d",&n,&m,&k))
13     {
14         int ans = 0;
15         for(int i=1;i<=n;i++)  scanf("%d",&a[i]);
16         int head1 = 1, tail1 = 0, head2 = 1, tail2 = 0;
17         int pre1 = 0, pre2 = 0;
18         for(int i=1;i<=n;i++)
19         {
20             while(head1<=tail1 && a[q1[tail1]]<=a[i])  tail1--;
21             while(head2<=tail2 && a[q2[tail2]]>=a[i])  tail2--;
22 
23             q1[++tail1] = q2[++tail2] = i;
24 
25             while(a[q1[head1]] - a[q2[head2]] > k)
26             {
27                 if(q1[head1] < q2[head2])  pre1 = q1[head1++];
28                 else  pre2 = q2[head2++];
29             }
30 
31             if(a[q1[head1]] - a[q2[head2]] >= m)
32             {
33                 ans = max(ans,i-max(pre1,pre2));
34             }
35         }
36         printf("%d
",ans);
37     }
38     return 0;
39 }
原文地址:https://www.cnblogs.com/zyb993963526/p/8051423.html