题目描述
Tz又耍畸形了!!他要当飞行员,他拿到了一个飞行员测试难度序列,他设定了一个难度差的最大值,
在序列中他想找到一个最长的子串,任意两个难度差不会超过他设定的最大值。耍畸形一个人是不行的,
于是他找到了你。
输入
第一行两个有空格隔开的整数k(0<=k<=2000,000,000),n(1<=n<=3000,000),k代表Tz设定的最大值,n代表难度序列的长度。
第二行为n个由空格隔开的整数ai(1<=ai<=2000,000,000),表示难度序列。
输出
最大的字串长度
样例输入
3 9
5 1 3 5 8 6 6 9 10
样例输出
4
提示
(有两个子串的长度为4: 5, 8, 6, 6 和8, 6, 6, 9.最长子串的长度就是4)
想法
- 优先队列基础题
算法
- 见代码
代码
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <cstring>
#include <string>
#include <cmath>
#include <queue>
#define MAXN 3000005
#define _(d) while(d((ch=getchar())>47&&ch<58))
using namespace std;
typedef long long ll;
ll k,ans,q1[MAXN],q2[MAXN];
int n,pos=1,x,l1=1,l2=1,r1,r2;
inline int get(){
char ch;bool flag=0;_(!) flag|=ch=='-';int x=ch-48;
_() x=(x<<3)+(x<<1)+ch-48;return flag?-x:x;
}
/*struct Node
{
int num;
ll v;
Node(){};
Node(int _num,ll _v){num=_num,v=_v;}
inline bool operator <(const Node &rhs)const{return v<rhs.v;}
};*/
ll a[MAXN];
//priority_queue<Node> q1;
//priority_queue<Node,vector<int>,greater<int> > q2;
//priority_queue<Node> q2;
int main()
{
//freopen("pilots.in","r",stdin);
//freopen("pilots.out","w",stdout);
k=get();n=get();
for (int i=1;i<=n;i++)
{
a[i]=get();
while(a[q1[r1]]<a[i]&&l1<=r1)r1--;q1[++r1]=i;
while(a[q2[r2]]>a[i]&&l2<=r2)r2--;q2[++r2]=i;
while(a[q1[l1]]-a[q2[l2]]>k)
{
pos++;
if(q1[l1]<pos)l1++;
if(q2[l2]<pos)l2++;
}
ans=max(ans,(ll)i-pos+1);
}
/*for (int i=1;i<=n;i++)
{
q1.push(Node(i,a[i]));
q2.push(Node(i,-a[i]));
while(q1.top().v+q2.top().v>k)
{
pos++;
while(!q1.empty()&&pos>q1.top().num)q1.pop();
while(!q2.empty()&&pos>q2.top().num)q2.pop();
//cout<<"ok"<<endl;
//cout<<pos<<endl;
}
ans=max(ans,(ll)i-pos+1);
//cout<<ans<<endl;
}*/
cout<<ans<<endl;
return 0;
}