首页 > 代码库 > HDU 3530 Subsequence(单调队列)
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
思路
维护两个单调队列,一个单调递增,维护最小值,一个单调递减,维护最大值。
#include<stdio.h>#include<string.h>const int maxn = 100005;int a[maxn],q1[maxn],q2[maxn];int main(){ int n,m,k; while (~scanf("%d%d%d",&n,&m,&k)) { int res = 0,pos = 0; memset(a,0,sizeof(a)); memset(q1,0,sizeof(q1)); memset(q2,0,sizeof(q2)); for (int i = 1;i <= n;i++) scanf("%d",&a[i]); int head1 = 1,head2 = 1,tail1 = 0,tail2 = 0; for (int i = 1;i <= n;i++) { while (head1 <= tail1 && a[i] <= a[q1[tail1]]) tail1--; //队头元素最小 q1[++tail1] = i; while (head2 <= tail2 && a[i] >= a[q2[tail2]]) tail2--; //队头元素最大 q2[++tail2] = i; while (head1 <= tail1 && head2 <= tail2 && a[q2[head2]] - a[q1[head1]] > k) { if (q1[head1]<q2[head2]) pos = q1[head1++]; else pos = q2[head2++]; } if (head1 <= tail1 && head2 <= tail2 && a[q2[head2]] - a[q1[head1]] >= m) res = res>(i-pos)?res:(i-pos); } printf("%d\n",res); } return 0;}
HDU 3530 Subsequence(单调队列)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。