P14058 的一种另类做法

· · 题解

这里讲一种不同与官解的做法,整体难度较高,但是个人认为具有启发性。

忽略环的条件,有一种显然的贪心策略:每次尽可能延长当前段,直到不能放再新建一段。正确性显然。

带上环的条件,我们破环为链,复制序列,维护一个数 x 能扩展到的最远的地方的后面一个位置 p_x。这东西显然可以单调序列维护,维护最大值最小值即可。

现在问题变成了从哪个位置 x 出发能跳最少的步数到达 x+n 的位置。

显然可以倍增,但是显然被卡了。

如果你做题经验比较丰富,你会发现现在这题跟 P3575 本质上是相同的。

就是我们有一种类似与并查集路径压缩的方法,fa_x 表示跳了 stp_x 步 x 能跳到的位置(fa_x 和 stp_x 动态维护)。初始时 fa_x=p_x,stp_x=1。 我们从第 1 个位置到第 n 个位置依次刷,设目前刷到第 x 个位置,那么就从 x 开始跳,直到 p_x \geq x+n 停止,再更新路径上所有点的 fa_x 和 stp_x 即可。整个过程实际上就是路径压缩,时效有了保证。而我们是依次从 1 刷到 n,终点不断向后移,正确性也有了保证。

然后你就把这题做掉了。

::::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;
}

::::