#HDU3530#Subsequence(单调队列)

来源:互联网 发布:知乎app for ios7.0 编辑:程序博客网 时间:2024/05/21 17:30

Subsequence

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 6721    Accepted Submission(s): 2255


Problem 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 01 1 1 1 15 0 31 2 3 4 5
 

Sample Output
54
 
题意:给出一个数列,求其中最长的子序列,满足序列中最大值和最小值的差不小于M,不大于K

维护两个单调队列,一个为上升,一个为下降

入队时维护单调性,判断两队列首项差是否大于K,

大于时编号靠前的一个先出队,并记录下它的编号

小于时不出队,因为后面很可能一个元素进来将整个队列清空,

只在满足不小于M时记录答案,

答案应该为当前编号 - 之前记录下来的较大编号

(因为记录编号时已经处于不合法状态,相对靠后编号的后一个将是合法状态)

StatusAcceptedTime265msMemory2840kBLength1077LangG++Submitted2017-05-24 15:53:14Shared

#include<iostream>#include<cstdio>#include<cstdlib>#include<cstring>#include<algorithm>using namespace std;const int Max = 100005;int N, M, K;int frob, backb, from, backm;int Qb[Max], Qm[Max], A[Max];void getint(int & num){    char c;    int flag = 1;    num = 0;    while((c = getchar()) < '0' || c > '9')    if(c == '-')    flag = -1;    while(c >= '0' && c <= '9'){    num = num * 10 + c - 48;    c = getchar();}    num *= flag;}int main(){while(~scanf("%d%d%d",&N, &M, &K)){for(int i = 1; i <= N; ++ i)getint(A[i]);frob = from = 1, backb = backm = 0;int lstb = 0, lstm = 0, Ans = 0;for(int i = 1; i <= N; ++ i){while(frob <= backb && A[i] > A[Qb[backb]])-- backb;Qb[++ backb] = i;while(from <= backm && A[i] < A[Qm[backm]])-- backm;Qm[++ backm] = i;while(A[Qb[frob]] - A[Qm[from]] > K){if(Qb[frob] < Qm[from])lstb = Qb[frob ++];else lstm = Qm[from ++];}if(A[Qb[frob]] - A[Qm[from]] >= M)Ans = max(Ans, i - max(lstb, lstm));}printf("%d\n", Ans);}return 0;}









原创粉丝点击