CF452F Permutation 题解

· · 题解

思路

考虑一个 O(n^2) 的暴力,枚举 i,j,i<j,当 pos_{2a_j-a_i}>j 时显然有解。但这个思路无法优化。(考场思路就到这里了)。

考虑其他的判断方式,对于一个点 a_i,若存在 d 使得 a_i-d,a_i+d 在 a_i 异侧,则显然有解,否则无解。考虑维护一个 01 序列 S,当枚举到 a_i 时,若 S_j=1 表示数字 j 在数字 a_i 之前出现过,则显然对于任意的 d,若能构成等差序列,当枚举到 a_i 时,S_{a_i-d}\neq S_{a_i+d}。因此可以得到一种判断方式:若枚举到 a_i 时,S 中以 a_i 为中心的最长子串是回文串,则不存在 d 使 a_i-d,a_i,a_i+d 能构成等差子序列。

这个操作可以用 bitset 维护,复杂度 O(\frac{n^2}{w}),但显然无法通过。考虑更加优秀的算法。发现时间瓶颈在于判断该子串是否为回文串,考虑使用哈希。维护 S 序列上每个子串的正哈希值与反哈希值。判断时只需要判断正反哈希值是否相同即可。这个步骤可以用线段树实现。

代码

AC记录

#include<bits/stdc++.h>
using namespace std;
const int NR=3e5+5;
uint64_t P=23;//使用自然溢出处理哈希
uint64_t p[NR];

int n;
int a[NR];
//线段树板子
struct Node{
    int l,r,len;
    uint64_t h1,h2;//h1正哈希,h2反哈希 
    friend Node operator +(const Node& a,const Node& b){
        Node c;
        c.l=min(a.l,b.l);
        c.r=max(a.r,b.r);
        c.h1=a.h1*p[b.len]+b.h1;
        c.h2=b.h2*p[a.len]+a.h2;
        c.len=a.len+b.len;
        return c;
    }
}tr[4*NR];
void build(int x,int l,int r){
    tr[x]={l,r,1,0,0};
    if(l==r) return;
    int mid=(l+r)>>1;
    build(x<<1,l,mid);
    build((x<<1)+1,mid+1,r);
    tr[x]=tr[x<<1]+tr[(x<<1)+1]; 
}
void update(int x,int p,bool k){
    if(p<tr[x].l||p>tr[x].r) return;
    if(p<=tr[x].l&&tr[x].r<=p){
        tr[x].h1=k;
        tr[x].h2=k;
        return;
    }
    update(x<<1,p,k);
    update((x<<1)+1,p,k);
    tr[x]=tr[x<<1]+tr[(x<<1)+1];
}
Node query(int x,int l,int r){
    if(r<tr[x].l||l>tr[x].r) return {r,l,0,0,0};
    if(l<=tr[x].l&&tr[x].r<=r) return tr[x];
    return query(x<<1,l,r)+query((x<<1)+1,l,r);
}

int main(){
    scanf("%d",&n);
    p[0]=1;
    for(int i=1;i<=n;i++){
        scanf("%d",&a[i]);
        p[i]=p[i-1]*P;
    }
    build(1,1,n);
    for(int i=1;i<=n;i++){
        update(1,a[i],1);
        int d=min(a[i]-1,n-a[i]);
        Node t=query(1,a[i]-d,a[i]+d);
        if(t.h1!=t.h2){
            printf("YES");
            return 0;
        }
    }
    printf("NO");
    return 0;
}