hdu 3530 Subsequence (尺取+rmq)

hdu 3530题目链接

题意:给出n个数,m,k,问最大的j-i+1,使得【i,j】间的最大值与最小值的差属于[m,k] 思路:rmq+尺取。 2A.

/* ***********************************************
Author :111qqz
Created Time :2016年05月19日 星期四 16时52分03秒
File Name :code/hdu/3530.cpp
************************************************ */

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <string>
#include <cmath>
#include <cstdlib>
#include <ctime>
#define fst first
#define sec second
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define ms(a,x) memset(a,x,sizeof(a))
typedef long long LL;
#define pi pair < int ,int >
#define MP make_pair

using namespace std;
const double eps = 1E-8;
const int dx4[4]={1,0,0,-1};
const int dy4[4]={0,-1,1,0};
const int inf = 0x3f3f3f3f;
const int N=1E5+7;
int n;
int a[N];
int dp[N][20],dp2[N][20];
int m,k;

void rmq_init()
{
    for ( int i  = 1 ; i <= n ; i ++)
	dp[i][0] = dp2[i][0] = a[i];

    for ( int j = 1 ; (1<<j) <= n ; j++)
	for ( int i = 1 ; i + (1<<j) -1 <= n ; i++)
	{
	    dp[i][j] = max(dp[i][j-1],dp[i+(1<<(j-1))][j-1]);
	    dp2[i][j]=min(dp2[i][j-1],dp2[i+(1<<(j-1))][j-1]);
	}
}

int rmq( int l,int r)
{
    int k = 0 ;
    while (1<<(k+1)<=r-l+1) k++;
    int mx = max(dp[l][k],dp[r-(1<<k)+1][k]);
    int mn = min(dp2[l][k],dp2[r-(1<<k)+1][k]);

    return mx-mn;
}

int ruler()
{
    int head = 1;
    int tail = 1;
    int res = -1 ;
    while (tail<=n)
    {
	int cur = rmq(head,tail);
	while (head<tail&&rmq(head,tail)>k) head++;
	while (tail<n&&rmq(head,tail)<m) tail++;
	//if (tail>n) break;
	cur = rmq(head,tail);
	if (cur>=m&&cur<=k)
	{
	    res = max(res,tail-head);
	}
//	cout<<"head:"<<head<<" tail:"<<tail<<" cur:"<<cur<<" res:"<<res<<endl;
	tail++;

    }
    return res+1;
}
int main()
{
	#ifndef  ONLINE_JUDGE 
	freopen("code/in.txt","r",stdin);
  #endif

	while (scanf("%d %d %d",&n,&m,&k)!=EOF)
	{
	    ms(dp,0);
	    for ( int i = 1 ; i  <= n ; i++) scanf("%d",&a[i]);
	    if (m>k)
	    {
		puts("0");
		continue;
	    }
	    rmq_init();
	    printf("%d\n",ruler());
	}



  #ifndef ONLINE_JUDGE  
  fclose(stdin);
  #endif
    return 0;
}