#HDU3530#Subsequence(单调队列)

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 0 1 1 1 1 1 5 0 3 1 2 3 4 5
 

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

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

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

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

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

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

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

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

Status Accepted
Time 265ms
Memory 2840kB
Length 1077
Lang G++
Submitted
Shared
#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;
}









  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值