题意:
给一个长度为n的序列,要求一个连续的子序列,其中最大的元素为maxx,最小的元素为minn,maxx-minn <= k。
要求这个连续子序列长度最长长度。
解析:
。。。
solo csu多校赛就搞出了第一道简单DP题,昨天和YYC看蓝桥杯的时候突然发现,这题好像可以暴力过去,10^4数据量。
开始的时候想用线段树去维护子序列的最大值和最小值,以为我算法的复杂度是O(nlogn),然后超时了。
因为枚举起点和终点必定要付出O(n^2)的代价。。。感觉自己有点sb。
今天来做,第一遍暴力过去,还是TLE。
想了一会,这TM要剪枝啊,当当前的最大值减去最小时已经超出k的范围的时候,果断break出去了。
然后就A了。
代码:
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <stack>
#include <vector>
#include <queue>
#include <map>
#include <climits>
#include <cassert>
#include <time.h>
#define LL long long
using namespace std;
const int maxn = 10000 + 10;
const int inf = 0x3f3f3f3f;
const double eps = 1e-8;
const double pi = acos(-1.0);
const double ee = exp(1.0);
int a[maxn];
int main()
{
#ifdef LOCAL
freopen("in.txt", "r", stdin);
#endif // LOCAL
int n, k;
while (~scanf("%d%d", &n, &k))
{
for (int i = 0; i < n; i++)
{
scanf("%d", &a[i]);
}
int ans = 0;
int maxx, minn;
for (int i = 0; i < n; i++)
{
maxx = a[i];
minn = a[i];
for (int j = i; j < n; j++)
{
if (maxx < a[j])
maxx = a[j];
if (a[j] < minn)
minn = a[j];
if (maxx - minn <= k)
{
if (ans < j - i + 1)
ans = j - i + 1;
}
else///剪枝!!!
{
break;
}
}
}
printf("%d\n", ans);
}
return 0;
}