1.LCS
LCS - Longest Common Substring
A string is finite sequence of characters over a non-empty finite set Σ.
In this problem, Σ is the set of lowercase letters.
Substring, also called factor, is a consecutive sequence of characters occurrences at least once in a string.
Now your task is simple, for two given strings, find the length of the longest common substring of them.
Here common substring means a substring of two or more strings.
Input
The input contains exactly two lines, each line consists of no more than 250000 lowercase letters, representing a string.
Output
The length of the longest common substring. If such string doesn’t exist, print “0” instead.
Example
Input:
alsdfkjfjkdsal
fdjskalajfkdsla
Output:
3
#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;
/*
* da函数中的m要小于SIZE;
* m可以开很大,前提是SIZE 也要开很大
*/
int const SIZE = 600000;
//分隔符,多串连接时需要用到,第0个为结束符,肯定用到
char const DELIMETER[] = {'#'};
int const DELIMETER_CNT = 1;
//字母表的字母个数
int const ALPHA_SIZE = DELIMETER_CNT + 26;
//char转int
inline int tr(char ch){
return ch - 'a' + 1;
}
//辅助数组,以下划线开头
int _wa[SIZE],_wb[SIZE],_wv[SIZE],_ws[SIZE];
//辅助函数
int _cmp(int const r[],int a,int b,int l){return r[a]==r[b]&&r[a+l]==r[b+l];}
//求后缀数组的倍增算法
//r: 源数组,且除r[n-1]外,其余r[i]>0
//n: r的长度
//m: r中的元素取值的上界,即任意r[i]<m
//sa:后缀数组,即结果
void da(int const r[],int n,int m,int sa[]){
int i,j,p,*x=_wa,*y=_wb,*t;
for(i=0;i<m;i++) _ws[i] = 0;
for(i=0;i<n;i++) _ws[x[i] = r[i]]++;
for(i=1;i<m;i++) _ws[i] += _ws[i-1];
for(i=n-1;i>=0;i--) sa[--_ws[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++) _wv[i]=x[y[i]];
for(i=0;i<m;i++) _ws[i]=0;
for(i=0;i<n;i++) _ws[_wv[i]]++;
for(i=1;i<m;i++) _ws[i] += _ws[i-1];
for(i=n-1;i>=0;i--) sa[--_ws[_wv[i]]] = y[i];
for(t=x,x=y,y=t,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++;
}
return;
}
//计算rank数组与height数组
//r: 源数组
//sa: 后缀数组
//n: 源数组的长度
//rank: rank数组,即计算结果
//height: height数组,即计算结果
void calHeight(int const r[],int const sa[],int n,int rank[],int height[]){
int i,j,k=0;
for(i=1;i<n;i++) rank[sa[i]]=i;
for(i=0;i<n-1;height[rank[i++]]=k)
for(k?k--:0,j=sa[rank[i]-1];r[i+k]==r[j+k];k++);
return;
}
void dispArray(int const a[],int n){
for(int i=0;i<n;++i)printf("%d ",a[i]);
printf("\n");
}
int R[SIZE],SA[SIZE];
int Rank[SIZE],Height[SIZE];
char A[600000];
int main(){
while( scanf("%s",A) != EOF ){
int n = strlen(A);
int mid = n;
A[n] = 'a';
scanf("%s",A+n+1);
n = strlen(A);
for (int i = 0;i < n ;++i)
R[i] = A[i] - 'a' + 1;
R[n++] = 0;
<span style="white-space:pre"> </span>R[mid] = 30;
da(R,n,32,SA);
calHeight(R,SA,n,Rank,Height); // 注意n是长度 跟上面一致
int ans_len = 0;
for (int i = 0;i < n;++i){
if ( Height[i] > 1){
if ( min(SA[i-1] ,SA[i] ) < mid && max(SA[i-1] ,SA[i]) > mid )
if ( ans_len < Height[i] ) ans_len = Height[i];
}
}
printf("%d\n",ans_len);
}
return 0;
}