WHU 1084 连续技(后缀数组)

题目链接:http://acm.whu.edu.cn/land/problem/detail?problem_id=1084

题意:给出一个数列,找出一个最长的长度大于1的连续子列,使得这个子列出现的次数大于1?

思路:求sa和h。二分答案。





int r[N],sa[N],wa[N],wb[N],wd[N],rank[N],h[N];



int cmp(int *r,int a,int b,int len)

{

    return r[a]==r[b]&&r[a+len]==r[b+len];

}



void da(int *r,int *sa,int n,int m)

{

    int i,j,p,*x=wa,*y=wb,*t;

    FOR0(i,m) wd[i]=0;

    FOR0(i,n) wd[x[i]=r[i]]++;

    FOR1(i,m-1) wd[i]+=wd[i-1];

    FORL0(i,n-1) sa[--wd[x[i]]]=i;

    for(j=1,p=1;p<n;j<<=1,m=p)

    {

        p=0;

        FOR(i,n-j,n-1) y[p++]=i;

        FOR0(i,n) if(sa[i]>=j) y[p++]=sa[i]-j;

        FOR0(i,m) wd[i]=0;

        FOR0(i,n) wd[x[i]]++;

        FOR1(i,m-1) wd[i]+=wd[i-1];

        FORL0(i,n-1) sa[--wd[x[y[i]]]]=y[i];

        t=x;x=y;y=t;p=1;x[sa[0]]=0;

        FOR1(i,n-1) x[sa[i]]=cmp(y,sa[i-1],sa[i],j)?p-1:p++;

    }

}







void calHeight(int *r,int *sa,int n)

{

    int i,j,k=0;

    FOR1(i,n) rank[sa[i]]=i;

    FOR0(i,n)

    {

        if(k) k--;

        j=sa[rank[i]-1];

        while(i+k<n&&j+k<n&&r[i+k]==r[j+k]) k++;

        h[rank[i]]=k;

    }

}



int C;

int n;

map<int,int> mp;

int s[N];



void add(int x,int val)

{

    while(x<N)

    {

        if(val>s[x]) s[x]=val;

        x+=x&-x;

    }

}



int get(int x)

{

    int ans=0;

    while(x>0)

    {

        if(s[x]>ans) ans=s[x];

        x-=x&-x;

    }

    return ans;

}



int f[N];



int cal(vector<int> V,int x)

{

    clr(s,0);

    sort(V.begin(),V.end());

    int i,ans=1;

    FOR0(i,SZ(V))

    {

        f[V[i]]=get(V[i])+1;

        ans=max(ans,f[V[i]]);

        add(V[i]+x,f[V[i]]);

    }

    return ans;

}



int OK(int x,int &cnt)

{

    cnt=0;

    int i,j,k,L,R;

    vector<int> V;

    FOR1(i,n)

    {

        L=i;

        while(L<=n&&h[L]<x) L++;

        R=L;

        while(R<=n&&h[R]>=x) R++;

        V.clear();

        FOR(j,L-1,R-1) V.pb(sa[j]);

        k=cal(V,x);

        cnt=max(cnt,k);

    }

    return cnt>1;

}









void deal()

{

    int low=2,high=n,mid,cnt;

    while(low<=high)

    {

        mid=(low+high)>>1;

        if(OK(mid,cnt)) low=mid+1;

        else high=mid-1;

    }

    if(low<=n&&OK(low,cnt)) PR(low,cnt);

    else if(high>=2&&OK(high,cnt)) PR(high,cnt);

    else puts("-1");

}



int main()

{

    while(scanf("%d",&n)!=-1)

    {

        mp.clear();

        int i,x=0;

        FOR0(i,n)

        {

            RD(r[i]);

            if(!mp[r[i]]) mp[r[i]]=++x;

            r[i]=mp[r[i]];

        }

        r[n]=0;

        da(r,sa,n+1,x+1);

        calHeight(r,sa,n);

        deal();

    }

    return 0;;

}

  

你可能感兴趣的:(后缀数组)