【后缀数组】 HDOJ 1403 Longest Common Substring

简单的后缀数组。。。先把输入的两个串连起来,也就是把第二个字符串连到第一个字符串后面,用一个没出现过的字符隔开。。。我这里用ascii 码 1 隔开。。然后用倍增算法求出sa数组,再求出height数组。。。那么height数组里中由两个分立在那个隔开的字符两边的后缀中的最大值显然是答案。。

#include <iostream>	
#include <sstream>	
#include <algorithm>	
#include <vector>	
#include <queue>	
#include <stack>	
#include <map>	
#include <set>	
#include <bitset>	
#include <cstdio>	
#include <cstring>	
#include <cstdlib>	
#include <cmath>	
#include <climits>	
#define maxn 200005
#define eps 1e-6 
#define mod 10007 
#define INF 99999999	
#define lowbit(x) (x&(-x))	
//#define lson o<<1, L, mid	
//#define rson o<<1 | 1, mid+1, R	
typedef long long LL;
using namespace std;

char s[maxn];
int c[maxn], t[maxn];
int t2[maxn], sa[maxn];
void build(int n, int m)
{
	int i, *x = t, *y = t2, k, p;
	for(i = 0; i < m; i++) c[i] = 0;
	for(i = 0; i < n; i++) c[x[i] = s[i]]++;
	for(i = 1; i < m; i++) c[i] += c[i-1];
	for(i = n-1; i >= 0; i--) sa[--c[x[i]]] = i;
	for(k = 1; k <= n; k<<=1) {
		p = 0;
		for(i = n-k; i < n; i++) y[p++] = i;
		for(i = 0; i < n; i++) if(sa[i] >= k) y[p++] = sa[i] - k;
		for(i = 0; i < m; i++) c[i] = 0;
		for(i = 0; i < n; i++) c[x[y[i]]]++;
		for(i = 1; i < m; i++) c[i] += c[i-1];
		for(i = n-1; i >= 0; i--) sa[--c[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]] == y[sa[i-1]] && y[sa[i]+k] == y[sa[i-1]+k] ? p-1 : p++;
		if(p >= n) break;
		m = p;
	}
}
int rank[maxn], height[maxn];
void getheight(int n)
{
	int i, j, k = 0;
	for(i = 1; i <= n; i++) rank[sa[i]] = i;
	for(i = 0; i < n; i++) {
		if(k) k--;
		j = sa[rank[i]-1];
		while(s[i+k] == s[j+k]) k++;
		height[rank[i]] = k;
	}
}
void debug(int n)
{
	int i;
	for(i = 0; i <= n; i++)
		printf("%d%d\n", height[i], sa[i]);
}
int main(void)
{
	int tmp, n, ans, i;	
	while(scanf("%s", s)!=EOF) {
		tmp = strlen(s);
		s[tmp] = 1;	
		scanf("%s", s+tmp+1);
		n = strlen(s);
		build(n+1, 128);
		getheight(n);
		ans = 0;
		for(i = 1; i <= n; i++) {
			if((sa[i]-tmp)*(sa[i-1]-tmp)<0)
				if(height[i] > ans)
					ans = height[i];
		}
		printf("%d\n", ans);
	}
	return 0;
}

你可能感兴趣的:(后缀数组,HDU)