HDU 1403 Longest Common Substring

好久没学新算法了,从现在开始努力吧。

花了3天时间看了后缀数组的论文,差不多看明白了,贴上一份应用的代码吧。

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <vector>
#include <map>
#include <queue>
#include <ctime>
#include <set>
#include <deque>
#include <string>
#define MP make_pair
#define PB push_back
#define SZ(x) ((int)(x).size())
#define REP(i,n) for (int _n=n,i=0; (i)<_n; ++(i))
#define FOR(i,a,b) for (int _b=b,i=(a);i<=_b;++(i))
#define FOREACH(it,c) for ( __typeof((c).begin()) it=(c).begin(),ite=(c).end(); it!=ite; ++it )
int rint() { int x; if(~scanf("%d",&x)) return x; return -1; }
typedef long long LL;
const int inf=~0U>>1;
using namespace std;

const int maxN=200010;
const int maxC=300;
int n,sa[maxN],height[maxN],top[maxN],rank[maxN],tmp[maxN],len1,ans;
string s;

void makesa(){
	memset(top,0,sizeof(top));
	REP(i,n) top[rank[i]=s[i]]++;
	for(int i=1;i<maxN;i++) top[i]+=top[i-1];
	REP(i,n) sa[--top[rank[i]]]=i;
	for(int len=1;len<n;len<<=1){
		int j=0;
		REP(i,n){
			j=sa[i]-len;
			if(j<0) j+=n;
			tmp[top[rank[j]]++]=j;
		}
		sa[tmp[top[0]=0]]=j=0;
		for(int i=1;i<n;i++){
			if(rank[tmp[i]]!=rank[tmp[i-1]]||rank[tmp[i]+len]!=rank[tmp[i-1]+len])
				top[++j]=i;
			sa[tmp[i]]=j;
		}
		memcpy(rank,sa,n*sizeof(int));
		memcpy(sa,tmp,n*sizeof(int));
		if(j>=n-1) return;
	}
}

void calheight(){
	int i,j,k;
	for(j=rank[height[i=k=0]=0];i<n-1;i++,k++){
		while(k>=0&&s[i]!=s[sa[j-1]+k]){
			height[j]=(k--);
			if((sa[j]<len1&&sa[j-1]>len1)||(sa[j]>len1&&sa[j-1]<len1)) {
				//puts("**");
				if(ans<height[j]) ans=height[j];
			}
			j=rank[sa[j]+1];
		}
	}
}

int main(){
#ifndef ONLINE_JUDGE
    freopen("a.in","r",stdin);
    freopen("a.out","w",stdout);
#endif
	string s1,s2;
	while(cin>>s1>>s2){
		len1=SZ(s1);
		s=s1+"$"+s2;
		n=s.size()+1;
		ans=0;
		makesa();
		calheight();
		cout<<ans<<endl;
	}
	return 0;
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值