码迷,mamicode.com
首页 > 其他好文 > 详细

hdu3530 Subsequence

时间:2015-05-16 11:57:35      阅读:127      评论:0      收藏:0      [点我收藏+]

标签:rmq

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

这题我用的是rmp算法,先初始化2的次方的区间最大值最小值,然后循环算出最大的区间长度。

#include<iostream>
#include<stdio.h>
#include<string.h>
#include<math.h>
#include<algorithm>
#include<map>
#include<string>
using namespace std;
int a[100006];
int minx[100100][30];
int maxx[100100][30];
void init_rmq(int n)
{
	int i,j;
	for(i=1;i<=n;i++)maxx[i][0]=minx[i][0]=a[i];
	for(j=1;j<=20;j++){
		for(i=1;i<=n;i++){
			if(i+(1<<j)-1<=n)
			{maxx[i][j]=max(maxx[i][j-1],maxx[i+(1<<(j-1))][j-1]);
			minx[i][j]=min(minx[i][j-1],minx[i+(1<<(j-1))][j-1]);}
		}
	}
}

int getmax(int l,int r)
{
	int k,i;
	if(l>r)swap(l,r);
	k=(log((r-l+1)*1.0)/log(2.0));
	return max(maxx[l][k],maxx[r-(1<<k)+1][k]);
}

int getmin(int l,int r)
{
	int k,i;
	if(l>r)swap(l,r);
	k=(log((r-l+1)*1.0)/log(2.0));
	return min(minx[l][k],minx[r-(1<<k)+1][k]);
}

int main()
{
	int n,m,i,j,k,l,r,ans,t;
	while(scanf("%d%d%d",&n,&m,&k)!=EOF)
	{
		for(i=1;i<=n;i++){
			scanf("%d",&a[i]);
		}
		init_rmq(n);
		l=1;ans=0;           //l不用每次从1开始判,因为之前的l越小,r-l+1的值就越大。
		for(i=1;i<=n;i++){
			r=i;
			if(l>r)continue;
			while(getmax(l,r)-getmin(l,r)>k)l++; //如果大于k,那么后面的r对于此时的l肯定不满足不大于k,所以必须l++;
			if(getmax(l,r)-getmin(l,r)>=m && getmax(l,r)-getmin(l,r)<=k)ans=max(ans,r-l+1);
		}
		printf("%d\n",ans);
	}
	return 0;
}



hdu3530 Subsequence

标签:rmq

原文地址:http://blog.csdn.net/kirito_acmer/article/details/45766855

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!