有多少個不同的子串?-- 後綴數組

 題目大意: 給你一個字符串問你有多少個不相同的子串?

Input

T- number of test cases. T<=20; Each test case consists of one string, whose length is <= 50000

output

For each test case output one number saying the number of distinct substrings.

Example

Input:
2
CCCCC
ABABA

Output:
5
9


題目思路:利用後綴數組這個工具,不會後綴數組詳見  後綴數組論文鏈接——處理字符串的有力工具_百度文庫。這篇文章說的比較詳細,思路就是一共會有 n*(n+1)/2  減去重複的就可以了,
舉個栗子.   ABABA  比如這個.他的後綴排序之後是:
• A  -------------------後綴 a
• ABA  ---------------後綴 b
• ABABA    ----------後綴 c
• BA  -----------------後綴 d
• BABA  -------------後綴 e
這樣,重複的子串就是 (a,b)的最長公共前綴長度
答案就是 15 - {  lcp(a,b)=1  } - {  lcp(b,c)=3  } - {  lcp(c,d)=0  } - {  lcp(d,e)=2  }
             =15-1-3-0-2=9;

下面是模板代碼

#include<cstdio>
#include<cstring>
#include<cctype>
#include<cmath>
#include<set>
#include<map>
#include<list>
#include<queue>
#include<deque>
#include<stack>
#include<string>
#include<vector>
#include<iostream>
#include<algorithm>
#include<stdlib.h>
#include<time.h>

using namespace std;
typedef long long LL;
const int INF=2e9+1e8;
const int MOD=1e9+7;
const int MAXSIZE=1e6+5;
const double eps=0.0000000001;
void fre()
{
    freopen("in.txt","r",stdin);
    freopen("out.txt","w",stdout);
}
#define memst(a,b) memset(a,b,sizeof(a))
#define fr(i,a,n) for(int i=a;i<n;i++)

int rankarr[MAXSIZE],wa[MAXSIZE],wb[MAXSIZE],height[MAXSIZE];
int wvarr[MAXSIZE],wsarr[MAXSIZE],SA[MAXSIZE];
char str[MAXSIZE];

int cmp(int *r,int a,int b,int l)
{
    return r[a]==r[b]&&r[a+l]==r[b+l];
}
void da(char *r,int *sa,int n,int m)
{
    int i,j,p,*x=wa,*y=wb,*t;
    for(i=0; i<m; i++) wsarr[i]=0;
    for(i=0; i<n; i++) wsarr[x[i]=r[i]]++;
    for(i=1; i<m; i++) wsarr[i]+=wsarr[i-1];
    for(i=n-1; i>=0; i--) sa[--wsarr[x[i]]]=i;
    for(j=1,p=1; p<n; j<<=1,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++) wvarr[i]=x[y[i]];
        for(i=0; i<m; i++) wsarr[i]=0;
        for(i=0; i<n; i++) wsarr[wvarr[i]]++;
        for(i=1; i<m; i++) wsarr[i]+=wsarr[i-1];
        for(i=n-1; i>=0; i--) sa[--wsarr[wvarr[i]]]=y[i];
        for(t=x,x=y,y=t,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++;
    }
    return;
}
void calheight(char *r,int *sa,int n)
{
    int i,j,k=0;
    for(i=1; i<=n; i++) rankarr[sa[i]]=i;
    for(i=0; i<n; height[rankarr[i++]]=k)
        for(k?k--:0,j=sa[rankarr[i]-1]; r[i+k]==r[j+k]; k++);
    return;
}
LL solve(int n)
{
    LL ans=n;
    for(int i=2;i<=n;i++)
        ans+=n-i+1-height[i];
    return ans;
}
int main()
{
    int ncase;
    cin>>ncase;
    while(ncase--)
    {
        scanf("%s",str);
        int n=strlen(str);
        str[n]=0;
        da(str,SA,n+1,128);
        calheight(str,SA,n);
        cout<<solve(n)<<endl;
    }
    return 0;
}



發佈了100 篇原創文章 · 獲贊 46 · 訪問量 11萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章