HDU 3518 Boring counting(后缀数组)

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=3518

题意:给出一个串。求至少出现两次且不重叠的子串的个数?

思路:求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;

    }

}



char s[N];

int n;





int cal(int len)

{

    int i,j,Min,Max,L,R,t,ans=0;

    u64 temp;

    FOR1(i,n)

    {

        L=i;

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

        if(L>n) break;

        R=L;

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

        Min=INF; Max=-INF;

        FOR(j,L-1,R-1)

        {

            Min=min(Min,sa[j]);

            Max=max(Max,sa[j]);

        }

        if(Max-Min>=len) ans++;

        i=R;

    }

    return ans;

}



void deal()

{

    i64 i,ans=0,temp;

    FOR1(i,n/2)

    {

        temp=cal(i);

        if(!temp) break;

        ans+=temp;

    }

    PR(ans);

}



int main()

{

    while(scanf("%s",s),s[0]!='#')

    {

        n=strlen(s);

        int i;

        FOR0(i,n) r[i]=s[i];

        r[n]=0;

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

        calHeight(r,sa,n);

        deal();

    }

    return 0;

}

  

你可能感兴趣的:(count)