P14058 的一种另类做法
Star_Meteor · · 题解
这里讲一种不同与官解的做法,整体难度较高,但是个人认为具有启发性。
忽略环的条件,有一种显然的贪心策略:每次尽可能延长当前段,直到不能放再新建一段。正确性显然。
带上环的条件,我们破环为链,复制序列,维护一个数
现在问题变成了从哪个位置
显然可以倍增,但是显然被卡了。
如果你做题经验比较丰富,你会发现现在这题跟 P3575 本质上是相同的。
就是我们有一种类似与并查集路径压缩的方法,
然后你就把这题做掉了。
::::success[代码] 注意你的时间和空间常数。
#include<bits/stdc++.h>
//#define int long long
using namespace std;
const int N=3e7+5;
int read(){
int ret=0,f=1;char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-f;ch=getchar();}
while(ch>='0'&&ch<='9')ret=ret*10+ch-'0',ch=getchar();
return ret*f;
}
void write(int x){
if(x<0)x=-x,putchar('-');
if(x>9)write(x/10);
putchar(x%10+'0');
}
int n,m;
int a[2*N];
int p[2*N],stp[2*N];
int que1[2*N],que2[2*N];
int ans;
inline int ask(int &x,int st){
if(x>=st+n)return 0;
stp[x]+=ask(p[x],st);//向后跳,更新 p 和 stp
int tt=stp[x];x=p[x];return tt;
}
signed main(){
int T=read();
while(T--){
n=read(),m=read();
for(int i=1;i<=n;i++)a[i]=read();
for(int i=n+1;i<=2*n;i++)a[i]=a[i-n];//断环为链
for(int i=1;i<=2*n;i++)que1[i]=que2[i]=0;
int hed1=1,til1=0,hed2=1,til2=0,pt=1;
for(int i=1;i<=2*n;i++){
while(hed1<=til1 && que1[hed1]<i)hed1++;
while(hed2<=til2 && que2[hed2]<i)hed2++;
while(pt!=2*n+1 && a[que1[hed1]]-a[que2[hed2]]<=m){
while(hed1<=til1 && a[que1[til1]]<=a[pt])til1--;que1[++til1]=pt;
while(hed2<=til2 && a[que2[til2]]>=a[pt])til2--;que2[++til2]=pt;
pt++;
}//双指针+两个优先队列维护极差
p[i]=pt-1;
}ans=n;
for(int i=1;i<=2*n;i++)stp[i]=1;
for(int i=1;i<=n;i++){
int now=i;
ans=min(ans,ask(now,i));
}
write(ans);putchar('\n');
}
return 0;
}
::::