hdu 1403 Longest Common Substring

Problem Description
Given two strings, you have to tell the length of the Longest Common Substring of them.

For example:
str1 = banana
str2 = cianaic

So the Longest Common Substring is "ana", and the length is 3.
 
 
   
Input
The input contains several test cases. Each test case contains two strings, each string will have at most 100000 characters. All the characters are in lower-case.

Process to the end of file.
 
 
   
Output
 For each test case, you have to tell the length of the Longest Common Substring of them.
//最长公共子串问题、、这题用我所知道的动态规划解法肯定是超时的、年前就试过了、
//后缀数组 、大一下学期见过一次,每个学期都会看一次
//到现在才自己会写了、、
//sa rank height h[i]=height[rank[i]] h[i]>=h[i-1]-1 .... 最有用的就是height了

//该题就是把两个串链接起来,然后判断height是否是合法的、、链接字符串中间是个 ‘$’ (不一定是这个,只要原串没出现过就可以了)

#include <iostream> #include <math.h> #include <vector> #include <queue> #include <stack> #include <stdio.h> #include <string.h> #include <algorithm> using namespace std; const int N=200010; int sa[N],w[N]; char s[N]; void suffix(int n,int m,int *x,int *y) { int i,j,p; for(i=0;i<=m;i++) w[i]=0; for(i=0;i<n;i++) w[x[i]=s[i]]++; for(i=1;i<=m;i++) w[i]+=w[i-1]; for(i=n-1;i>=0;i--) sa[--w[x[i]]]=i; for(j=1;j<=n;j=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++) w[i]=0; for(i=0;i<n;i++) w[ x[y[i]] ]++; for(i=1;i<=m;i++) w[i]+=w[i-1]; for(i=n-1;i>=0;i--) sa[ --w[x[y[i]]] ]=y[i]; swap(x,y);p=1; x[sa[0]]=0; for(i=1;i<n;i++) x[sa[i]]=y[sa[i-1]]==y[sa[i]]&&y[sa[i-1]+j]==y[sa[i]+j]?p-1:p++; if(p>=n) break; m=p; } } int x[N],y[N]; // height int rank[N],height[N]; void get_height(int n) { int i,k,j; for(i=0;i<n;i++) rank[sa[i]]=i; for(k=i=0;i<n;i++) { if(k) k--; if(rank[i]==0){k=0;continue;} j=sa[rank[i]-1]; // little problem while(s[i+k]==s[j+k]) k++; height[rank[i]]=k; } } int main() { while(scanf("%s",s)!=EOF) { int len=strlen(s); s[len]='$'; scanf("%s",s+len+1); int n=strlen(s); // printf("%s ",s); suffix(n,'z',x,y); get_height(n); int Max=0; int l,r; for(int i=1;i<n;i++) { // printf("%d\n",height[i]); if(height[i]>Max) { l=sa[i]; r=sa[i-1]; if( (l<len&&r>len)||(l>len&&r<len) ) Max=height[i]; } } printf("%d\n",Max); } return 0; }

 

你可能感兴趣的:(substring)