题面
Sol
都是求最长公共子串,\(hihocoder\)上讲的很清楚
把两个串拼在一起,中间用一个特殊字符隔开
那么答案就是排序后相邻两个不同串的后缀的\(height\)
为什么呢?
如果答案为不相邻的两个后缀的前缀,计算它们最长前缀时必定要跨越过这些中间\(height\)值,也就是选相邻的两个一定要比不选相邻的两个更优
# include <bits/stdc++.h>
# define IL inline
# define RG register
# define Fill(a, b) memset(a, b, sizeof(a))
using namespace std;
typedef long long ll;
const int _(200010);
IL ll Read(){
RG char c = getchar(); RG ll x = 0, z = 1;
for(; c < '0' || c > '9'; c = getchar()) z = c == '-' ? -1 : 1;
for(; c >= '0' && c <= '9'; c = getchar()) x = (x << 1) + (x << 3) + (c ^ 48);
return x * z;
}
int n, a[_], sa[_], rk[_], y[_], h[_], height[_], t[_], ans;
char A[_], B[_];
IL bool Cmp(RG int i, RG int j, RG int k){ return y[i] == y[j] && y[i + k] == y[j + k]; }
IL void Sort(){
RG int m = 27;
for(RG int i = 1; i <= n; ++i) ++t[rk[i] = a[i]];
for(RG int i = 1; i <= m; ++i) t[i] += t[i - 1];
for(RG int i = n; i; --i) sa[t[rk[i]]--] = i;
for(RG int k = 1; k <= n; k <<= 1){
RG int l = 0;
for(RG int i = n - k + 1; i <= n; ++i) y[++l] = i;
for(RG int i = 1; i <= n; ++i) if(sa[i] > k) y[++l] = sa[i] - k;
for(RG int i = 0; i <= m; ++i) t[i] = 0;
for(RG int i = 1; i <= n; ++i) ++t[rk[y[i]]];
for(RG int i = 1; i <= m; ++i) t[i] += t[i - 1];
for(RG int i = n; i; --i) sa[t[rk[y[i]]]--] = y[i];
swap(rk, y); rk[sa[1]] = l = 1;
for(RG int i = 2; i <= n; ++i) rk[sa[i]] = Cmp(sa[i - 1], sa[i], k) ? l : ++l;
if(l >= n) break; m = l;
}
for(RG int i = 1; i <= n; ++i){
h[i] = max(0, h[i - 1] - 1);
if(rk[i] == 1) continue;
while(a[i + h[i]] == a[sa[rk[i] - 1] + h[i]]) ++h[i];
}
for(RG int i = 1; i <= n; ++i) height[i] = h[sa[i]];
}
IL bool Diff(RG int a, RG int b, RG int c){ return (a <= c && b > c) || (a > c && b <= c); }
int main(RG int argc, RG char* argv[]){
scanf(" %s %s", A, B); RG int l1 = strlen(A), l2 = strlen(B);
for(RG int i = 0; i < l1; ++i) a[++n] = A[i] - 'a' + 1; a[++n] = 27;
for(RG int i = 0; i < l2; ++i) a[++n] = B[i] - 'a' + 1;
Sort();
for(RG int i = 2; i <= n; ++i)
if(Diff(sa[i - 1], sa[i], l1)) ans = max(ans, height[i]);
printf("%d\n", ans);
return 0;
}
原文地址:https://www.cnblogs.com/cjoieryl/p/8340148.html
时间: 2024-11-03 22:45:00