Repeated Substrings
String analysis often arises in applications from biology and chemistry, such as the study of DNA and protein molecules. One interesting problem is to find how many substrings are repeated (at least twice) in a long string. In this problem, you will write a program to find the total number of repeated substrings in a string of at most 100 000 alphabetic characters. Any unique substring that occurs more than once is counted. As an example, if the string is “aabaab”, there are 5 repeated substrings: “a”, “aa”, “aab”, “ab”, “b”. If the string is “aaaaa”, the repeated substrings are “a”, “aa”, “aaa”, “aaaa”. Note that repeated occurrences of a substring may overlap (e.g. “aaaa” in the second case).
Input
The input consists of at most 10 cases. The first line contains a positive integer, specifying the number of
cases to follow. Each of the following line contains a nonempty string of up to 100 000 alphabetic characters.
Output
For each line of input, output one line containing the number of unique substrings that are repeated. You
may assume that the correct answer fits in a signed 32-bit integer.
Sample Input
3 aabaab aaaaa AaAaA
Sample Output
5 4 5
题目链接:https://cn.vjudge.net/problem/CSU-1632
题目大意:求字符串中至少出现两次的子串的个数
思路:因为要保证之前记录过的不会重复记录,所以只有hi>hi-1时才加上hi-hi-1,具体见代码。
代码:
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
#define ll long long
const int N=100005;
int a[N],id[N],sa[N],rak[N],h[N],c[N],t1[N],t2[N];
bool cmp(int *f,int x,int y,int w){return f[x]==f[y]&&f[x+w]==f[y+w];}
void da(int a[], int sa[], int rak[], int h[], int n, int m)
{
n++;
int i,j,p,*x = t1,*y = t2;
for (i=0; i<m; i++) c[i]=0;
for (i=0; i<n; i++) c[x[i]=a[i]]++;
for (i=1; i<m; i++) c[i]+=c[i-1];
for (i=n-1; i>=0; i--) sa[--c[x[i]]]=i;
for (j=1; j<=n; j<<=1)
{
p=0;
for (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<m; i++) c[i]=0;
for (i=0; i<n; i++) c[x[y[i]]]++;
for (i=1; i<m; i++) c[i]+=c[i-1];
for (i=n-1; i>=0; i--) sa[--c[x[y[i]]]]=y[i];
swap(x, y); p=1; x[sa[0]]=0;
for (i=1; i<n; i++) x[sa[i]]=cmp(y, sa[i-1], sa[i], j)?p-1:p++;
if(p>=n) break;
m=p;
}
n--;
for(i=0;i<=n;i++) rak[sa[i]]=i;
int k=0;
for(int i=0;i<n;h[rak[i++]]=k)
for(k=k?k-1:k,j=sa[rak[i]-1];a[i+k]==a[j+k];k++);
}
char s[N];
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
scanf("%s",s);
int n=strlen(s);
for(int i=0;i<n;i++) a[i]=s[i];
a[n]=0;
da(a,sa,rak,h,n,127);
int ans=0,p=0;
for(int i=2;i<=n;i++)
{
if(h[i]>p){ans+=h[i]-p;p=h[i];}
else p=h[i];
}
printf("%d\n",ans);
}
return 0;
}