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; }

 

转载于:https://www.cnblogs.com/372465774y/archive/2013/05/03/3058386.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值