$Z$ 函数
https://www.luogu.com.cn/problem/P5410
题意概述:给定字符串 \(a\),\(b\),求 \(b\) 的 \(Z\) 函数数组,即 \(b\) 与 \(b\) 的每个后缀的最长公共子串长度;以及 \(b\) 与 \(a\) 的每个后缀的最长公共子串长度。
参考 \(manacher\) 算法,逐步拓展,\(E\) 数组的构建过程要借助 \(Z\) 数组,形式基本一致。
//author:kzssCCC
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
void solve(){
string a,b;
cin >> a >> b;
int l1 = a.size();
int l2 = b.size();
vector<int> z(l2),e(l1);
{
z[0] = l2;
int r=0,c=0;
for (int i=1;i<l2;i++){
int len = r>i?min(r-i,z[i-c]):0;
while (i+len<l2 && b[i+len]==b[len]){
len++;
}
if (i+len>r){
r = i+len;
c = i;
}
z[i] = len;
}
}
{
int r=0,c=0;
for (int i=0;i<l1;i++){
int len = r>i?min(r-i,z[i-c]):0;
while (i+len<l1 && len<l2 && a[i+len]==b[len]){
len++;
}
if (i+len>r){
r = i+len;
c = i;
}
e[i] = len;
}
}
ll res1 = 0;
for (int i=0;i<l2;i++){
res1 ^= (i+1ll)*(z[i]+1);
}
ll res2 = 0;
for (int i=0;i<l1;i++){
res2 ^= (i+1ll)*(e[i]+1);
}
cout << res1 << '\n';
cout << res2 << '\n';
}
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
int t = 1;
// cin >> t;
while (t--) solve();
return 0;
}

浙公网安备 33010602011771号