1553: Good subsequence
Time Limit: 2 Sec Memory Limit: 256 MBSubmit: 234 Solved: 59
[ 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
题意:求n的数列中的子序列是的这个子序列的最大值减去最小值的差小于等于k,求最长的子序列的长度;
直接暴力,注意优化即可
代码:
#include <stdio.h>
#include <stdlib.h>
#define N 10010
#define inf 0x3f3f3f3f
int a[N];
int main()
{
int n,k;
while(~scanf("%d%d",&n,&k))
{
int i,j;
for(i=0; i<n; i++)
{
scanf("%d",&a[i]);
}
int max1,min1,ans=0;
for(i=0; i<n; i++)
{
min1=inf,max1=0;
for(j=i; j<n; j++)
{
if(max1<a[j])
max1=a[j];
if(min1>a[j])
min1=a[j];
if((max1-min1)<=k&&ans<(j-i+1))
{
ans=j-i+1;
}
else if((max1-min1)>k)这是一个重要的剪枝
{
break;
}
}
}
printf("%d\n",ans);
}
return 0;
}