题目链接:http://codeforces.com/problemset/problem/427/D
大意是寻找两个字符串中最短的公共子串,要求子串在两个串中都是唯一的。
造一个S#T的串,做后缀数组,从小到大枚举子串长度在height数组中扫描,如果某一个组中来自两个串的数量分别为1,就找到了答案。
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <string.h>
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <ctime>
#include <numeric>
#include <cassert> using namespace std; const int N=;; char s[N]; struct SuffixArray {
int wa[N], wb[N], cnt[N], wv[N];
int rk[N], height[N];
int sa[N];
bool cmp(int r[], int a, int b, int l) {
return r[a] == r[b] && r[a+l] == r[b+l];
}
void calcSA(char r[], int n, int m) {
int i, j, p, *x = wa, *y = wb;
for (i = ; i < m; ++i) cnt[i] = ;
for (i = ; i < n; ++i) cnt[x[i]=r[i]]++;
for (i = ; i < m; ++i) cnt[i] += cnt[i-];
for (i = n-; i >= ; --i) sa[--cnt[x[i]]] = i;
for (j = , p = ; p < n; j *= , m = p) {
for (p = , i = n - j; i < n; ++i) y[p++] = i;
for (i = ; i < n; ++i) if (sa[i] >= j) y[p++] = sa[i] - j;
for (i = ; i < n; ++i) wv[i] = x[y[i]];
for (i = ; i < m; ++i) cnt[i] = ;
for (i = ; i < n; ++i) cnt[wv[i]]++;
for (i = ; i < m; ++i) cnt[i] += cnt[i-];
for (i = n-; i >= ; --i) sa[--cnt[wv[i]]] = y[i];
for (swap(x, y), p = , x[sa[]] = , i = ; i < n; ++i)
x[sa[i]] = cmp(y, sa[i-], sa[i], j) ? p- : p++;
}
}
void calcHeight(char r[], int n) {
int i, j, k = ;
for (i = ; i <= n; ++i) rk[sa[i]] = i;
for (i = ; i < n; height[rk[i++]] = k)
for (k?k--:, j = sa[rk[i]-]; r[i+k] == r[j+k]; k++);
}
bool solve(int k,int n,int div) {
int ca=,cb=;
for (int i=;i<=n;i++) {
if (height[i]<k) {
if (ca==&&cb==)
return true;
ca=;cb=;
if (sa[i]<div) ca++;
else if (sa[i]>div) cb++;
continue;
}
if (sa[i]<div) ca++;
else if (sa[i]>div) cb++;
}
return ca==&&cb==;
}
}suf; char a[N],b[N]; int main(){
scanf("%s %s",a,b);
int n=strlen(a),m=strlen(b);
strcpy(s,a);
s[n]='#';
strcpy(s+n+,b);
int tot=n+m+;
suf.calcSA(s,tot+,);
suf.calcHeight(s,tot);
int ret=-;
for (int i=;i<=n;i++) {
if (suf.solve(i,tot,n)) {
ret=i;
break;
}
}
printf("%d\n",ret);
return ;
}