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;
}
┆ 凉 ┆ 暖 ┆ 降 ┆ 等 ┆ 幸 ┆ 我 ┆ 我 ┆ 里 ┆ 将 ┆ ┆ 可 ┆ 有 ┆ 谦 ┆ 戮 ┆ 那 ┆ ┆ 大 ┆ ┆ 始 ┆ 然 ┆
┆ 薄 ┆ 一 ┆ 临 ┆ 你 ┆ 的 ┆ 还 ┆ 没 ┆ ┆ 来 ┆ ┆ 是 ┆ 来 ┆ 逊 ┆ 没 ┆ 些 ┆ ┆ 雁 ┆ ┆ 终 ┆ 而 ┆
┆ ┆ 暖 ┆ ┆ 如 ┆ 地 ┆ 站 ┆ 有 ┆ ┆ 也 ┆ ┆ 我 ┆ ┆ 的 ┆ 有 ┆ 精 ┆ ┆ 也 ┆ ┆ 没 ┆ 你 ┆
┆ ┆ 这 ┆ ┆ 试 ┆ 方 ┆ 在 ┆ 逃 ┆ ┆ 会 ┆ ┆ 在 ┆ ┆ 清 ┆ 来 ┆ 准 ┆ ┆ 没 ┆ ┆ 有 ┆ 没 ┆
┆ ┆ 生 ┆ ┆ 探 ┆ ┆ 最 ┆ 避 ┆ ┆ 在 ┆ ┆ 这 ┆ ┆ 晨 ┆ ┆ 的 ┆ ┆ 有 ┆ ┆ 来 ┆ 有 ┆
┆ ┆ 之 ┆ ┆ 般 ┆ ┆ 不 ┆ ┆ ┆ 这 ┆ ┆ 里 ┆ ┆ 没 ┆ ┆ 杀 ┆ ┆ 来 ┆ ┆ ┆ 来 ┆

浙公网安备 33010602011771号