Bzoj4566:[HAOI2016]找相同字符
题面
Sol
两个串拼在一起后求出后缀数组
然后显然的\(n^2\)暴力,就是直接枚举求\(LCP\)
又由于扫的时候是对\(height\)取\(min\)
那么可以用单调栈维护每一段的贡献相同的
# include <bits/stdc++.h>
# define RG register
# define IL inline
# define Fill(a, b) memset(a, b, sizeof(a))
using namespace std;
typedef long long ll;
const int _(4e5 + 5);
int n, a[_], is[_], rk[_], sa[_], height[_], tmp[_], t[_];
int S[_], top, s1[_], s2[_];
ll ans, sum[_];
char ss[_];
IL int Cmp(RG int i, RG int j, RG int k){
return tmp[i] == tmp[j] && tmp[i + k] == tmp[j + k] && i + k <= n && j + k <= n;
}
IL void Suffix_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) tmp[++l] = i;
for(RG int i = 1; i <= n; ++i) if(sa[i] > k) tmp[++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[tmp[i]]];
for(RG int i = 1; i <= m; ++i) t[i] += t[i - 1];
for(RG int i = n; i; --i) sa[t[rk[tmp[i]]]--] = tmp[i];
swap(rk, tmp), 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, h = 0; i <= n; ++i){
if(h) --h;
while(a[i + h] == a[sa[rk[i] - 1] + h]) ++h;
height[rk[i]] = h;
}
}
int main(RG int argc, RG char* argv[]){
scanf(" %s", ss);
for(RG int i = 0, len = strlen(ss); i < len; ++i) a[++n] = ss[i] - 'a' + 1, is[n] = 1;
scanf(" %s", ss), a[++n] = 27;
for(RG int i = 0, len = strlen(ss); i < len; ++i) a[++n] = ss[i] - 'a' + 1, is[n] = 2;
Suffix_Sort();
for(RG int i = 1; i < n; ++i)
s1[i] = s1[i - 1] + (is[sa[i]] == 1), s2[i] = s2[i - 1] + (is[sa[i]] == 2);
S[0] = 1;
for(RG int i = 1; i < n; ++i){
while(top && height[S[top]] > height[i]) --top;
S[++top] = i, sum[top] = sum[top - 1] + (s1[i - 1] - s1[S[top - 1] - 1]) * height[i];
if(is[sa[i]] == 2) ans += sum[top];
}
top = 0;
for(RG int i = 1; i < n; ++i){
while(top && height[S[top]] > height[i]) --top;
S[++top] = i, sum[top] = sum[top - 1] + (s2[i - 1] - s2[S[top - 1] - 1]) * height[i];
if(is[sa[i]] == 1) ans += sum[top];
}
printf("%lld\n", ans);
return 0;
}