Problem G: Good subsequence
Time Limit: 2 Sec Memory Limit: 256 MBSubmit: 202 Solved: 44
[ Submit][ Status][ Web Board]
Description
Give you a sequence of n numbers, and a number k you should find the max length of Good subsequence. Good subsequence is a continuous subsequence of the given sequence and its maximum value - minimum value<=k. For example n=5, k=2, the sequence ={5, 4, 2, 3, 1}. The answer is 3, the good subsequence are {4, 2, 3} or {2, 3, 1}.
Input
There are several test cases.
Each test case contains two line. the first line are two numbers indicates n and k (1<=n<=10,000, 1<=k<=1,000,000,000). The second line give the sequence of n numbers a[i] (1<=i<=n, 1<=a[i]<=1,000,000,000).
The input will finish with the end of file.
Output
For each the case, output one integer indicates the answer.
Sample Input
5 2
5 4 2 3 1
1 1
1
Sample Output
3
1
HINT
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <string>
#include <vector>
#include <set>
#include <map>
#include <queue>
#include <stack>
#include <sstream>
#include <iomanip>
using namespace std;
const int INF=0x4fffffff;
const int EXP=1e-6;
const int MS=10005;
const int MS2=100005;
int a[MS];
int n,k;
int minv[MS][15];
int maxv[MS][15];
int RMQ_init()
{
for(int i=0;i<n;i++)
{
minv[i][0]=a[i];
maxv[i][0]=a[i];
}
for(int j=1;(1<<j)<=n;j++)
{
for(int i=0;i+(1<<j)-1<n;i++)
{
minv[i][j]=min(minv[i][j-1],minv[i+(1<<(j-1))][j-1]);
maxv[i][j]=max(maxv[i][j-1],maxv[i+(1<<(j-1))][j-1]);
}
}
}
int RMQ(int l,int r)
{
int k=0;
while(1<<(k+1)<=r-l+1)
k++;
return max(maxv[l][k],maxv[r-(1<<k)+1][k])-min(minv[l][k],minv[r-(1<<k)+1][k]);
}
int main()
{
while(scanf("%d%d",&n,&k)!=EOF)
{
for(int i=0;i<n;i++)
scanf("%d",&a[i]);
RMQ_init();
int ans=0;
bool flag=true;
/*
for(int len=n;len>0&&flag;len--)
{
for(int i=0;i+len-1<n&&flag;i++)
if(RMQ(i,i+len-1)<=k)
{
ans=len;
flag=false;
}
}
*/
for(int i=0;i<n;i++)
{
int l=i;
int r=n-1;
while(l<=r)
{
int mid=(l+r)/2;
int t=RMQ(i,mid);
if(t>k)
r=mid-1;
else
l=mid+1;
}
if(ans<l-i)
ans=l-i;
}
cout<<ans<<endl;
}
return 0;
}
注意下标是从零开始的,如果题中给的是从一开始注意减一