HDU 3530 單調佇列

_rabbit發表於2014-05-13

Subsequence

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


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


題意:求一個最長子序列,使得最大值與最小值差值在mi,mx範圍內,

用一個遞增,一個遞減兩個單調佇列維護最大值,最小值,然後掃描一遍,佇列的起點從最近一個被單調佇列拋棄的下標+1算起。

程式碼:

/* ***********************************************
Author :_rabbit
Created Time :2014/5/13 10:30:48
File Name :C.cpp
************************************************ */
#pragma comment(linker, "/STACK:102400000,102400000")
#include <stdio.h>
#include <iostream>
#include <algorithm>
#include <sstream>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <string>
#include <time.h>
#include <math.h>
#include <queue>
#include <stack>
#include <set>
#include <map>
using namespace std;
#define INF 0x3f3f3f3f
#define eps 1e-8
#define pi acos(-1.0)
typedef long long ll;
int a[100100],que1[100100],que2[100100];
int main()
{
     //freopen("data.in","r",stdin);
     //freopen("data.out","w",stdout);
     int n,mx,mi;
     while(~scanf("%d%d%d",&n,&mi,&mx)){
         for(int i=1;i<=n;i++)scanf("%d",&a[i]);
         int head1=0,tail1=0,head2=0,tail2=0;
		 int last1=0,last2=0;
         int ans=0;
         for(int i=1;i<=n;i++){
             while(head1<tail1&&a[que1[tail1-1]]>a[i])tail1--;//遞增
             que1[tail1++]=i;
             while(head2<tail2&&a[que2[tail2-1]]<a[i])tail2--;//遞減
             que2[tail2++]=i;
             while(a[que2[head2]]-a[que1[head1]]>mx){
                 if(que1[head1]<que2[head2])head1++;
                 else head2++;
             }
             if(a[que2[head2]]-a[que1[head1]]>=mi)
                 ans=max(ans,i-max(que1[head1-1],que2[head2-1]));
         }
         cout<<ans<<endl;
     }
     return 0;
}



相關文章