首页 > 代码库 > poj 2774 Long Long Message(后缀数组)

poj 2774 Long Long Message(后缀数组)

??

题意:给定两个字符串A 和B。求最长公共子串。

思路:将两个字符串连接起来中间用一个没出现过的符号切割。

所以答案为满足后缀在不同的串中且height值最大的height值

#include<cstdio>  
#include<cstring>  
#include<cmath>  
#include<cstdlib>  
#include<iostream>  
#include<algorithm>  
#include<vector>  
#include<map>  
#include<queue>  
#include<stack> 
#include<string>
#include<map> 
#include<set>
#define eps 1e-6 
#define LL long long  
using namespace std;  

const int maxn = 200000 + 200;
//const int INF = 0x3f3f3f3f;
char str1[100010], str2[100010];

struct SuffixArray {  
	
    int s[maxn];      /// 原始字符数组(最后一个字符应必须是0,而前面的字符必须非0)  
    int sa[maxn];     // 后缀数组,sa[0]一定是n-1,即最后一个字符  
    int rank[maxn];   // 名次数组  
    int height[maxn]; // height数组  
    int t[maxn], t2[maxn], c[maxn]; // 辅助数组  
    int n; // 字符个数  
  
    void clear() { n = 0; memset(sa, 0, sizeof(sa)); }  
  
    /// m为最大字符值加1。!!! 调用之前需设置好s和n  
    void build_sa(int m) {  
 	    int i, *x = t, *y = t2;  
    	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(int k = 1; k <= n; k <<= 1) {  
      		int 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 = 0; 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-1]]==y[sa[i]] && y[sa[i-1]+k]==y[sa[i]+k] ? p-1 : p++;  
      		if(p >= n) break;  
      		m = p;  
    	}  
  	}  
  
    void build_height() {  
    	int i, j, k = 0;  
    	for(i = 0; 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;  
    	}  
  	}  
} sa;

void init() {
	sa.clear();
	int len1 = strlen(str1), len2 = strlen(str2);
	for(int i = 0; i < len1; i++) sa.s[i] = str1[i] - ‘a‘ + 1;
	for(int i = 0; i < len2; i++) sa.s[len1+i+1] = str2[i] - ‘a‘ + 1;
	sa.s[len1] = 27; sa.s[len1+len2+1] = 0;
	sa.n = len1 + len2 + 2;
	sa.build_sa(30);
	sa.build_height();
}

void solve() {
	int ans = 0;
	int len1 = strlen(str1);
	for(int i = 1; i < sa.n; i++) {
		if(sa.height[i] > ans)
			if(sa.sa[i-1]<len1&&sa.sa[i]>len1 || sa.sa[i]<len1&&sa.sa[i-1]>len1)
				ans = sa.height[i]; 
	}
	cout << ans << endl;
}

int main() {
	//freopen("input.txt", "r", stdin);
	while(scanf("%s%s", str1, str2) == 2) {
		init();
		solve();
	}
	return 0;
}





poj 2774 Long Long Message(后缀数组)