题目:http://poj.org/problem?id=2774
题目大意:就是给你2个字符串,让你输出他们的最长公共子串。
思路:拼起来,构造后缀数组,然后二分答案,判断一遍扫 height 数组就行了。
代码如下:
#include<cstdio> #include<cstring> #include<algorithm> using namespace std; const int MAXN = 111111 << 1; char str[MAXN]; int sa[MAXN],rank[MAXN],height[MAXN]; int t[MAXN],t2[MAXN],c[MAXN]; void get_height(int n) { for(int i = 1;i <= n;i++) rank[sa[i]] = i; int k = 0; for(int i = 0;i < n;i++) { if(k) k--; int j = sa[rank[i]-1]; while(str[i+k] == str[j+k]) k++; height[rank[i]] = k; } } void da(int n,int m) { int *x = t,*y = t2; for(int i = 0;i < m;i++) c[i] = 0; for(int i= 0;i < n;i++) c[x[i] = str[i]]++; for(int i = 1;i < m;i++) c[i] += c[i-1]; for(int i = n-1;i >= 0;i--) sa[--c[x[i]]] = i; for(int k = 1;k <= n;k <<= 1) { int p = 0; for(int i = n-k;i < n;i++) y[p++] = i; for(int i = 0;i < n;i++) if(sa[i] >= k) y[p++] = sa[i] - k; for(int i = 0;i < m;i++) c[i] = 0; for(int i = 0;i < n;i++) c[x[y[i]]]++; for(int i = 1;i < m;i++) c[i] += c[i-1]; for(int i = n-1;i >= 0;i--) sa[--c[x[y[i]]]] = y[i]; swap(x,y); p = 1; x[sa[0]] = 0; for(int 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; } get_height(n-1); } int na; int dif(int a,int b) { if(a > b) swap(a,b); if(a < na && b > na) return 1; else return 0; } int check(int mid,int n) { for(int i = 2;i <= n;i++) { if(dif(sa[i],sa[i-1]) && height[i] >= mid) return 1; } return 0; } int slove(int n) { int l = 1,r = na; int ans = 0; while(l <= r) { int mid = (l+r) >> 1; //printf("l = %d,r = %d,mid = %d\n",l,r,mid); if(check(mid,n)) { ans = mid; l = mid + 1; } else r = mid - 1; } return ans; } int main() { while(~scanf("%s",str)) { int n = strlen(str); na = n; str[n] = 127; scanf("%s",str+n+1); n = strlen(str); //for(int i = 0;i < n;i++) //printf("i = %d,s = %d\n",i,str[i]); da(n+1,256); printf("%d\n",slove(n)); } return 0; }