题目:
http://lightoj.com/volume_showproblem.php?problem=1428题意:
求母串中的不相同的并且不包含匹配串的子串个数。
思路:
求不相同子串个数和明显用后缀数组可以搞,然后处理不包含匹配串的情况只要kmp跑一遍找到所有包含的位置,然后从而确定母串中所有位置能够匹配的最远距离。
具体就是找到所有的匹配位置之后可以确定这些位置的最大匹配长度是lenp-1,然后倒着扫一遍整个串,每个不是匹配位置的位置的最大匹配长度就是后一位的匹配长度加一。由此得到每一位的最大匹配长度,然后跑一遍后缀数组,找到所有不相同后缀子串个数,同时减去每一位的无法匹配的部分就是答案了。
代码:
//kopyh
#include <bits/stdc++.h>
#define INF 0x3f3f3f3f
#define MOD 1000000007
#define N 50010
using namespace std;
int n,m,sum,res,flag;
int rmax[N];
char s[N],ss[N];
void getNext(char *pre, int len, int *next)
{
int i = 0,j = -1;
next[0] = -1;
while(i < len)
{
if(j == -1 || pre[i] == pre[j])
{
i++,j++;
if(pre[i]!=pre[j]) next[i] = j;
else next[i] = next [j];
}
else j = next[j];
}
}
void kmp(char *str, char *pre)
{
int lenp = strlen(pre), lens = strlen(str);
int next[lenp+1];
getNext(pre, lenp, next);
int i,j; i=j=0;
while(i < lens)
{
if(j == -1 || str[i] == pre[j]) i++, j++;
else j = next[j];
if(j == lenp)
rmax[i-lenp]=lenp-1;
}
}
int seq[N], sa[N], ranks[N], height[N];
int wwa[N], wwb[N], wws[N], wwv[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 n, int m)
{
int i, j, p, *x = wwa, *y = wwb;
for (i = 0; i < m; ++i) wws[i] = 0;
for (i = 0; i < n; ++i) wws[x[i]=r[i]]++;
for (i = 1; i < m; ++i) wws[i] += wws[i-1];
for (i = n-1; i >= 0; --i) sa[--wws[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) wwv[i] = x[y[i]];
for (i = 0; i < m; ++i) wws[i] = 0;
for (i = 0; i < n; ++i) wws[wwv[i]]++;
for (i = 1; i < m; ++i) wws[i] += wws[i-1];
for (i = n-1; i >= 0; --i) sa[--wws[wwv[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 n)
{
int i, j, k = 0;
for (i = 1; i <= n; ++i) ranks[sa[i]] = i;
for (i = 0; i < n; height[ranks[i++]] = k)
for (k?k--:0, j = sa[ranks[i]-1]; r[i+k] == r[j+k]; k++);
}
int main()
{
int i,j,k,cas,T,t,x,y,z;
scanf("%d",&T);
cas=0;
while(T--)
{
scanf("%s%s",&s,&ss);
memset(rmax,-1,sizeof(rmax));
n=strlen(s);m=27;
kmp(s,ss);rmax[n]=0;
for(i=n-1;i>=0;i--)
if(rmax[i]==-1)
rmax[i]=rmax[i+1]+1;
for(i=0;i<n;i++)
seq[i]=s[i]-'a'+1;
seq[n]=0;
da(seq,n+1,m);
calheight(seq,n);
long long res=0;
for(i=1;i<=n;i++)
{
x=height[i];
y=min(rmax[sa[i]],n-sa[i]);
if(y-x>0)res+=y-x;
}
printf("Case %d: %lld\n",++cas,res);
}
return 0;
}