SPOJ DISUBSTR Distinct Substrings 后缀数组子串个数

#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <algorithm>
using namespace std;

const int N = 100005;
int wa[N], wb[N], ws[N], wv[N];
int rk[N], height[N];

bool cmp(int r[], int a, int b, int l) {
    return r[a] == r[b] && r[a+l] == r[b+l];
}

void da(int r[], int sa[], int n, int m) {
    int i, j, p, *x = wa, *y = wb;
    for (i = 0; i < m; ++i) ws[i] = 0;
    for (i = 0; i < n; ++i) ws[x[i]=r[i]]++;
    for (i = 1; i < m; ++i) ws[i] += ws[i-1];
    for (i = n-1; i >= 0; --i) sa[--ws[x[i]]] = i;
    for (j = 1, p = 1; p < n; j *= 2, m = p) {
        for (p = 0, i = n - j; i < n; ++i) y[p++] = i;
        for (i = 0; i < n; ++i) if (sa[i] >= j) y[p++] = sa[i] - j;
        for (i = 0; i < n; ++i) wv[i] = x[y[i]];
        for (i = 0; i < m; ++i) ws[i] = 0;
        for (i = 0; i < n; ++i) ws[wv[i]]++;
        for (i = 1; i < m; ++i) ws[i] += ws[i-1];
        for (i = n-1; i >= 0; --i) sa[--ws[wv[i]]] = y[i];
        for (swap(x, y), p = 1, x[sa[0]] = 0, i = 1; i < n; ++i)
            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;
    for (i = 1; i <= n; ++i) rk[sa[i]] = i;
    for (i = 0; i < n; height[rk[i++]] = k)
        for (k?k--:0, j = sa[rk[i]-1]; r[i+k] == r[j+k]; k++);
}

int str[N],sa[N];
char ss[N];

int main()
{
    int i,m,n;
    scanf("%d",&m);
    while(m--)
    {
        scanf("%s",ss);
        n=strlen(ss);
        memset(sa,0,sizeof(sa));
        memset(str,0,sizeof(str));
        for(i=0;i<n;i++)
            str[i]=ss[i];
        str[n]=0;
        da(str,sa,n+1,128);
        calheight(str,sa,n);
        //for(i=0;i<=n;i++)
            //printf("%d %d\n",i,rk[i]);
        int ans=0;
        for(i=1;i<=n;i++)
        {
            ans+=n-sa[i]-height[i];
        }
        printf("%d\n",ans);

    }
    return 0;
}

你可能感兴趣的:(SPOJ DISUBSTR Distinct Substrings 后缀数组子串个数)