转载请注明出处,谢谢http://blog.csdn.net/acm_cxlove/article/details/7854526 by---cxlove
题目:给出一个A串,给出若干个B串,问A串中有多少个不同的子串不是B中的子串
http://acm.hdu.edu.cn/showproblem.php?pid=4416
之前用SA做过一次,http://blog.csdn.net/acm_cxlove/article/details/8013942
刚学SAM,再来一次,但是花了我好长时间啊,sad
先把A串建立SAM,然后把所有的B串跑一遍LCS,记录A中每个位置的最大长度,最后拿len减掉匹配的长度。
但是有一些地方需要注意:
首先是A中不同的子串,这点要去重,首先把匹配的长度初始化为pre的len,也就是初始情况下就把重复的子串去掉。
接下来就是每跑一遍B串,需要向pre更新,开始的做法是跑一遍拓扑之后
每次都去更新,类似 SPOJ的LCS2,果断T了
看了zz1215的做法,瞬间明白了,当匹配到某个节点之后,pre表示的串是当前串的后缀,必然出现过,所以把pre的匹配长度都置为len,这样每个结点只需要更新一次
记忆化一下,果断就能过了
不过哭瞎,SA和SAM效率差不多
#include<iostream>
#include<cstdio>
#include<map>
#include<cstring>
#include<cmath>
#include<vector>
#include<algorithm>
#include<set>
#include<string>
#include<queue>
#define inf 1600005
#define M 40
#define N 210001
#define maxn 2000005
#define eps 1e-7
#define zero(a) fabs(a)<eps
#define Min(a,b) ((a)<(b)?(a):(b))
#define Max(a,b) ((a)>(b)?(a):(b))
#define pb(a) push_back(a)
#define mp(a,b) make_pair(a,b)
#define mem(a,b) memset(a,b,sizeof(a))
#define LL long long
#define MOD 1000000007
#define lson step<<1
#define rson step<<1|1
#define sqr(a) ((a)*(a))
#define Key_value ch[ch[root][1]][0]
#define test puts("OK");
#define pi acos(-1.0)
#define lowbit(x) ((x)&(-(x)))
#pragma comment(linker, "/STACK:1024000000,1024000000")
#define vi vector<int>
using namespace std;
struct SAM{
SAM *pre,*son[26];
int len,ml;
}*root,*tail,que[N],*b[N];
int tot;
char str[N/2];
void add(int c,int l){
SAM *np=&que[tot++],*p=tail;
np->len=l;tail=np;
while(p&&p->son[c]==NULL) p->son[c]=np,p=p->pre;
if(p==NULL) np->pre=root;
else{
SAM *q=p->son[c];
if(p->len+1==q->len) np->pre=q;
else{
SAM *nq=&que[tot++];
*nq=*q;
nq->len=p->len+1;
np->pre=q->pre=nq;
while(p&&p->son[c]==q) p->son[c]=nq,p=p->pre;
}
}
}
bool vis[N];
void Update(SAM *p){
if(p==NULL||vis[p-que]) return;
p->ml=p->len;
vis[p-que]=true;
Update(p->pre);
}
int main(){
//freopen("input.txt","r",stdin);
int t,cas=0,n;
scanf("%d",&t);
while(t--){
scanf("%d%s",&n,str);
tot=0;mem(vis,false);
root=tail=&que[tot++];
for(int i=0;str[i];i++)
add(str[i]-'a',i+1);
for(int i=0;i<tot;i++) if(que[i].pre) que[i].ml=que[i].pre->len;
while(n--){
scanf("%s",str);
SAM *p=root;
int len=0;
for(int i=0;str[i];i++){
int c=str[i]-'a';
if(p->son[c]!=NULL) len++,p=p->son[c],Update(p->pre);
else{
while(p&&p->son[c]==NULL) p=p->pre;
if(p==NULL) len=0,p=root;
else len=p->len+1,p=p->son[c],Update(p->pre);
}
p->ml=Max(len,p->ml);
}
}
LL ans=0;
for(int i=0;i<tot;i++){
// printf("%d %d\n",que[i].len,que[i].ml);
ans+=que[i].len-que[i].ml;
}
printf("Case %d: %I64d\n",++cas,ans);
for(int i=0;i<tot;i++){
que[i].ml=0;
que[i].pre=NULL;
mem(que[i].son,NULL);
}
}
return 0;
}