csu 1305 Substring (后缀数组)

时间:2023-03-08 20:50:36
csu 1305 Substring (后缀数组)

http://acm.csu.edu.cn/OnlineJudge/problem.php?id=1305

1305: Substring

Time Limit: 2 Sec  Memory Limit: 10 MB Submit: 12  Solved: 2 [Submit][Status][Web Board]

Description

Given a string s. The length of s is smaller than 1000. You are to caculate the number of different substrings of s.

Input

There are multiple test cases. Each test case contains one line, with a string s.You may assume that s only contains lowercase letters. You may assume that there are only ten test cases with the length of string s is bigger than 400.

Output

For each test case, you are only to output one integer,  the answer.

Sample Input

a
ac
abcd

Sample Output

1
3
10 【题解】:
后缀数组:用(1+2+。。。+len)-(height数组之后)
【code】:
 #include <iostream>
#include<string.h>
#include<stdio.h> using namespace std; #define maxn 10100
#define cls(x) memset(x, 0, sizeof(x))
int wa[maxn],wb[maxn],wv[maxn],wss[maxn];
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)
{
cls(wa);
cls(wb);
cls(wv);
cls(wss);
int i,j,p,*x=wa,*y=wb,*t;
for(i=;i<m;i++) wss[i]=;
for(i=;i<n;i++) wss[x[i]=r[i]]++;
for(i=;i<m;i++) wss[i]+=wss[i-];
for(i=n-;i>=;i--) sa[--wss[x[i]]]=i;
for(j=,p=;p<n;j*=,m=p)
{
for(p=,i=n-j;i<n;i++) y[p++]=i;
for(i=;i<n;i++) if(sa[i]>=j) y[p++]=sa[i]-j;
for(i=;i<n;i++) wv[i]=x[y[i]];
for(i=;i<m;i++) wss[i]=;
for(i=;i<n;i++) wss[wv[i]]++;
for(i=;i<m;i++) wss[i]+=wss[i-];
for(i=n-;i>=;i--) sa[--wss[wv[i]]]=y[i];
for(t=x,x=y,y=t,p=,x[sa[]]=,i=;i<n;i++)
x[sa[i]]=cmp(y,sa[i-],sa[i],j)?p-:p++;
}
return;
}
int rank[maxn],height[maxn];
void calheight(char *r,int *sa,int n)
{
cls(rank);
cls(height);
int i,j,k=;
for(i=;i<n;i++) rank[sa[i]]=i;
for(i=;i<n;height[rank[i++]]=k)
for(k?k--:,j=sa[rank[i]-];r[i+k]==r[j+k]&&i!=j;k++);
return;
} char ca[maxn * ];
int sa[maxn]; int main()
{
while (cin >> ca)
{
int len = strlen(ca);
da(ca, sa, len+, );
calheight(ca,sa,len+);
int i,sum=;
for(i=;i<=len;i++)
{
sum+=height[i];
}
cout<<len*(len+)/-sum<<endl;
cls(ca);
}
return ;
}