您的位置:首页 > 其它

POJ - 3415 Common Substrings 求2个串大于K的公共子串个数

2017-09-18 10:14 417 查看
题目:求2个串大于K的公共子串个数

思路:对第一个串建立SAM,通过拓扑序,算出每个节点在串中的出现次数,然后用第二个串去跑SAM,match[i]表示i节点的经过次数

代码:

#pragma comment(linker, "/STACK:1024000000,1024000000")
#include<iostream>
#include<algorithm>
#include<ctime>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<string>
#include<vector>
#include<map>
#include<set>
#include<queue>
#include<stack>
#include<list>
#include<numeric>
using namespace std;
#define LL long long
#define ULL unsigned long long
#define INF 0x3f3f3f3f
#define mm(a,b) memset(a,b,sizeof(a))
#define PP puts("*********************");
template<class T> T f_abs(T a){ return a > 0 ? a : -a; }
template<class T> T gcd(T a, T b){ return b ? gcd(b, a%b) : a; }
template<class T> T lcm(T a,T b){return a/gcd(a,b)*b;}
// 0x3f3f3f3f3f3f3f3f
//0x3f3f3f3f

const int MAXN = 200050, SIZE = 52;
int getid(char ch){
if(ch>='A'&&ch<='Z') return ch-'A'+26;
else return ch-'a';
}
struct SAM {
int len[MAXN], link[MAXN], next[MAXN][SIZE];
int total, last;
inline int newNode(int L) {
len[++total] = L; link[total] = 0;
for(int i = 0; i < SIZE; ++i) next[total][i] = 0;
return total;
}
inline void Add(int c) {
int i, p = last, cur = newNode(len[last] + 1);
for(; p && !next[p][c]; p = link[p]) next[p][c] = cur;
if(!p) link[cur] = 1;//令其指向初始状态
else {
int q = next[p][c];
if(len[q] == len[p] + 1) link[cur] = q;
else {//>
int clone = newNode(len[p] + 1);
for(i = 0; i < SIZE; ++i) next[clone][i] = next[q][i];
link[clone] = link[q];
link[q] = link[cur] = clone;
for(; p && next[p][c] == q; p = link[p]) next[p][c] = clone;
}
}
last = cur;
}
void Init () {//根节点是1
total = 0;
last = newNode(0);
}
}sam;
char str[MAXN];
int num[MAXN],idx[MAXN],tim[MAXN],match[MAXN];
int main(){

int K;
while(~scanf("%d",&K)){
if(K==0)
break;
scanf("%s",str);
sam.Init();
for(int i=0;str[i]!='\0';i++)
sam.Add(getid(str[i]));
for(int i=1;i<=sam.total;i++)
num[i]=tim[i]=match[i]=0;
for(int i=1;i<=sam.total;i++) num[sam.len[i]]++;
for(int i=1;i<=sam.total;i++) num[i]+=num[i-1];
for(int i=1;i<=sam.total;i++) idx[num[sam.len[i]]--]=i;
int now=1,len=0;
for(int i=0;str[i]!='\0';i++){
int c=getid(str[i]);
now=sam.next[now][c];
tim[now]++;
}
for(int i=sam.total;i>=1;i--){
int p=idx[i],np=sam.link[p];
tim[np]+=tim[p];
}
scanf("%s",str);
now=1,len=0;
LL sum=0;
for(int i=0;str[i]!='\0';i++){
int c=getid(str[i]);
if(sam.next[now][c]){
len++;
now=sam.next[now][c];
}
else{
while(sam.next[now][c]==0&&now!=0)
now=sam.link[now];
if(now==0){
now=1;
len=0;
}
else{
len=sam.len[now]+1;
now=sam.next[now][c];
}
}
if(len>=K){
int L=sam.len[sam.link[now]];
sum+=(LL)tim[now]*(len-max(L,K-1));
if(sam.len[sam.link[now]]>=K)
match[sam.link[now]]++;
}
}
for(int i=sam.total;i>=1;i--){
int p=idx[i];
int np=sam.link[p];
int L=sam.len[np];
int x=max(0,sam.len[p]-max(L,K-1));
sum+=(LL)x*match[p]*tim[p];
if(sam.len[np]>=K)
match[np]+=match[p];
}
printf("%lld\n",sum);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: